Skip to content

Instantly share code, notes, and snippets.

@Xinguang
Created June 9, 2017 01:12
Show Gist options
  • Save Xinguang/74039646ce1738b8605222d5898f2ec2 to your computer and use it in GitHub Desktop.
Save Xinguang/74039646ce1738b8605222d5898f2ec2 to your computer and use it in GitHub Desktop.
package envy
import (
"flag"
"fmt"
"os"
"strings"
)
// Parse takes a string p that is used
// as the environment variable prefix
// for each flag configured.
func Parse(p string) {
// Build a map of explicitly set flags.
set := map[string]bool{}
flag.CommandLine.Visit(func(f *flag.Flag) {
set[f.Name] = true
})
flag.CommandLine.VisitAll(func(f *flag.Flag) {
// Create an env var name
// based on the supplied prefix.
envVar := fmt.Sprintf("%s_%s", p, strings.ToUpper(f.Name))
envVar = strings.Replace(envVar, "-", "_", -1)
// Update the Flag.Value if the
// env var is non "".
if val := os.Getenv(envVar); val != "" {
// Update the value if it hasn't
// already been set.
if defined := set[f.Name]; !defined {
flag.CommandLine.Set(f.Name, val)
}
}
// Append the env var to the
// Flag.Usage field.
f.Usage = fmt.Sprintf("%s [%s]", f.Usage, envVar)
})
}
///////////////
package main
import (
"flag"
"fmt"
"github.com/jamiealquiza/envy"
)
func main() {
var address = flag.String("address", "127.0.0.1", "Some random address")
var port = flag.String("port", "8131", "Some random port")
envy.Parse("MYAPP") // looks for MYAPP_ADDRESS & MYAPP_PORT
flag.Parse()
fmt.Println(*address)
fmt.Println(*port)
}

Output:

Prints flag defaults

% ./example 127.0.0.1 8131

Flag defaults overridden

% MYAPP_ADDRESS="0.0.0.0" MYAPP_PORT="9080" ./example 0.0.0.0 9080

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment