This is a simple library that allows that enables reading the value of flags from environment variables.
The Go flags package is well-thought-out, battle-tested, and extensively used, but modern deployment practices tend to favour storing configuration in environment variables rather than passing them in on the command-line.
envflag
and its predecessors bridge this gap by mapping environment variables onto flags.
Import this package, and use envflag.Parse
instead of flag.Parse
:
package main
import (
"flag"
"github.com/csmith/envflag"
)
var (
myFlag = flag.String("my-flag", "woohoo", "Something or other")
)
func main() {
envflag.Parse()
println(*myFlag)
}
In its default configuration, envflag
will:
- Map all flag names to appropriate environment variable names (
my-flag
->MY_FLAG
) - Update the usage information of flags to include the environment variable name
- Show usage and exit with an appropriate status code on error
- Use the default set of flags provided by
flag.CommandLine
- Call
flag.Parse
to also parse any command-line flags
You can customise the behaviour of envflag
by passing in options:
envflag.Parse(envflag.WithPrefix("MYAPP_"))
Changes the mapping of environment variables to always include the given prefix
(e.g. my-flag
-> MYAPP_MY_FLAG
).
envflag.Parse(envflag.WithFlagSet(someFlagSet))
Use the given flag.FlagSet
instead of flag.CommandLine
.
envflag.Parse(envflag.WithShowInUsage(false))
Suppresses the default behaviour of updating flag usage to include the environment variable names.
envflag.Parse(envflag.WithArguments([]string{"-option1", "-option2"}))
When parsing the command-line arguments, use the given slice instead of os.Args[1:]
.
Released under the MIT licence. See LICENCE for full details.
Heavily inspired by kouhin/envflag which does mostly the same job but can't easily add prefixes and is a bit harder to configure.
Contributions are welcome! Please feel free to open issues or send pull requests.