goconfig
is a lightweight library that populates your Go structs from command
line flags, environment variables and JSON configuration files. It aims to make
configuration straightforward while keeping your code idiomatic.
- Unified configuration from flags, environment variables and JSON files
- Hierarchical keys using struct fields
- Supports arrays,
time.Duration
, and most native flag types - Auto-generated
-help
with usage information
go get github.com/fulldump/goconfig
Define your configuration struct with descriptive tags:
type myconfig struct {
Name string `usage:"The name of something"`
EnableLog bool `usage:"Enable logging into logdb" json:"enable_log"`
MaxProcs int `usage:"Maximum number of procs"`
UsersDB db
LogDB db
}
type db struct {
Host string `usage:"Host where db is located"`
User string `usage:"Database user"`
Pass string `usage:"Database password"`
}
Provide defaults and read the configuration:
c := &myconfig{
EnableLog: true,
UsersDB: db{
Host: "localhost",
User: "root",
Pass: "123456",
},
}
goconfig.Read(c)
Running your program with -help
prints automatically generated help text:
Usage of example:
-enablelog
Enable logging into logdb [env ENABLELOG] (default true)
-logdb.host string
Host where db is located [env LOGDB_HOST] (default "localhost")
-logdb.pass string
Database password [env LOGDB_PASS] (default "123456")
-logdb.user string
Database user [env LOGDB_USER] (default "root")
-maxprocs int
Maximum number of procs [env MAXPROCS]
-name string
The name of something [env NAME]
-usersdb.host string
Host where db is located [env USERSDB_HOST]
-usersdb.pass string
Database password [env USERSDB_PASS]
-usersdb.user string
Database user [env USERSDB_USER]
goconfig
supports the basic types from the flag
package plus arrays and
nested structs:
- bool
- float64
- int64
- int
- string
- uint64
- uint
- struct (hierarchical keys)
- array (any type)
The time.Duration
type is fully supported and can be provided as a
duration string (e.g. "15s"
) or as nanoseconds.
Uses the standard flag
behaviour to display help.
Read configuration from a JSON file. Given the previous configuration structure,
a sample config.json
looks like:
{
"name": "Fulanito",
"usersdb": {
"host": "localhost",
"user": "admin",
"pass": "123"
}
}
If the -config flag is not provided, Goconfig will look for a file named
config.json
in the current working directory and load it if present.
Configuration precedence (highest to lowest):
- Command line arguments
- Environment variables
- JSON config file
- Default values
Contributions are welcome! Feel free to fork the repository, submit pull requests, or open an issue if you encounter problems or have suggestions.
Run the full test suite with:
make
This repository includes a small example. Build it with:
make example
Goconfig is released under the MIT License.