I'm working on my first real Go project and have been searching for some tools to handle the configuration.
Finally, I've found this tool: https://github.com/spf13/viper which is really nice but I have some issues when I try to handle some more complex configurations such as the following config.yaml example:
app:
name: "project-name"
version 1
models:
modelA:
varA: "foo"
varB: "bar"
modelB:
varA: "baz"
varB: "qux"
varC: "norf"
I don't know how to get the values from modelB for example. While looking at the lib code, I've found the followings but I don't really understand how to use it:
// Marshals the config into a Struct
func Marshal(rawVal interface{}) error {...}
func AllSettings() map[string]interface{} {...}
What I want is to be able, from everywhere in my package, to do something like:
modelsConf := viper.Get("models")
fmt.Println(modelsConf["modelA"]["varA"])
Could someone explain me the best way to achieve this?
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.
Viper will read a config string (as JSON, TOML, YAML, HCL or envfile) retrieved from a path in a Key/Value store such as etcd or Consul. These values take precedence over default values, but are overridden by configuration values retrieved from disk, flags, or environment variables.
Since the "models" block is a map, it's a bit easier to call
m := viper.GetStringMap("models")
m will be a map[string]interface {}
Then, you get the value of m[key], which is an interface {}, so you cast it to map[interface {}]interface {} :
m := v.GetStringMap("models")
mm := m["modelA"].(map[interface{}]interface{})
Now you can access "varA" key passing the key as an interface {} :
mmm := mm[string("varA")]
mmm is foo
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