Created
October 23, 2018 05:02
-
-
Save andrewmeissner/77601994d0df0f433784a633a9313c78 to your computer and use it in GitHub Desktop.
Attach environment variables to standard library flags
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"flag" | |
"fmt" | |
"os" | |
"strings" | |
) | |
package main() { | |
flags := flag.NewFlagSet("run", flag.ContinueOnError) | |
flags.String("port", "7777", "port on which app will listen and serve") | |
flags.VisitAll(func (f *flag.Flag) { | |
envVar := strings.Replace(strings.ToUpper(fmt.Sprintf("prefix_%s", f.Name)), "-", "_", -1) | |
if val, ok := os.LookupEnv(envVar); ok { | |
flags.Set(f.Name, val) | |
} | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Precedence