flagga is an extensible Go library for handling program configuration using (but not limited to) command line arguments, environment variables and JSON.
This idea and API come from Peter Bourgon's Go for Industrial Programming talk at Gophercon Iceland 2018.
It should work as a drop-in replacement for the standard library flag
package. The only difference is the fact that NewFlagSet
and Init
accept a second string for the description.
- Be able to configure a program with different sources that have different priorities.
- Be extensible so anyone can extend the API to provide different sources to get their configuration from (yaml, toml, database?, ...).
- Be a drop-in replacement for the Go standard
flag
package with extra features. - Have no third-party dependencies.
go get github.com/erizocosmico/flagga
Or use your preferred dependency manager such as dep or vgo.
var fs flagga.FlagSet
db := fs.String("db", defaultDBURI, "database connection string", flagga.Env("DBURI"))
users := fs.StringList("users", nil, "list of allowed users", flagga.JSON("users"))
err := fs.Parse(os.Args[1:], flagga.JSONVia("config.json"), flagga.EnvPrefix("MYAPP_"))
if err != nil {
// handle err
}
fmt.Println(*db) // Outputs: "user@localhost:1234/foo"
fmt.Println(strings.Join(*users, ", ")) // Outputs: "jane, joe, alice"
To get the previous results we can invoke the program in the following ways:
echo '{"users":["jane", "joe", "alice"]}' > config.json
./myprogram -db=user@localhost:1234/foo -users=jane -users=joe -users=alice
MYAPP_DBURI=user@localhost:1234/foo ./myprogram
CLI flags always have priority over environment variables or JSON keys. If a flag is provided using the command line flags, no other sources will be checked for that variable.
The rest of the priorities depend of the order in which the sources are passed to the Parse
method. For example, fs.Parse(os.Args, flagga.EnvPrefix("FOO_"), flagga.JSONVia("cfg"))
gives more priority to environment variables than to the JSON configuration.
Env
: from environment variable sources.JSON
: from JSON sources.
YAML and TOML extractors are available in the flaggax repository.
EnvPrefix
: provides all environment variables matching the given prefix.JSONVia
: provides the content of the JSON in the given file.
YAML and TOML sources are available in the flaggax repository.
You can implement your own Source
s and Extractor
s in case your configuration is in a different format. Check out the Source
and Extractor
interfaces in the package documentation.
MIT, see LICENSE