I'm new at Go programming, and I'm wondering: what is the preferred way to handle configuration parameters for a Go program (the kind of stuff one might use properties files or ini files for, in other contexts)?
Application configuration has remained largely static for most of our lifetime, using flags, environment variables and files. Any change has usually required restarting the application or significant complexity in code to signal and reload the config.
Viper is a complete configuration solution for Go applications including 12-Factor apps. It is designed to work within an application, and can handle all types of configuration needs and formats. It supports: setting defaults. reading from JSON, TOML, YAML, HCL, envfile and Java properties config files.
The JSON format worked for me quite well. The standard library offers methods to write the data structure indented, so it is quite readable.
See also this golang-nuts thread.
The benefits of JSON are that it is fairly simple to parse and human readable/editable while offering semantics for lists and mappings (which can become quite handy), which is not the case with many ini-type config parsers.
Example usage:
conf.json:
{ "Users": ["UserA","UserB"], "Groups": ["GroupA"] }
Program to read the configuration
import ( "encoding/json" "os" "fmt" ) type Configuration struct { Users []string Groups []string } file, _ := os.Open("conf.json") defer file.Close() decoder := json.NewDecoder(file) configuration := Configuration{} err := decoder.Decode(&configuration) if err != nil { fmt.Println("error:", err) } fmt.Println(configuration.Users) // output: [UserA, UserB]
Another option is to use TOML, which is an INI-like format created by Tom Preston-Werner. I built a Go parser for it that is extensively tested. You can use it like other options proposed here. For example, if you have this TOML data in something.toml
Age = 198 Cats = [ "Cauchy", "Plato" ] Pi = 3.14 Perfection = [ 6, 28, 496, 8128 ] DOB = 1987-07-05T05:45:00Z
Then you can load it into your Go program with something like
type Config struct { Age int Cats []string Pi float64 Perfection []int DOB time.Time } var conf Config if _, err := toml.DecodeFile("something.toml", &conf); err != nil { // handle error }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With