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?
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
You can simply use:
m := viper.Get("models.modelA")
or
newViperForModelA := viper.Sub("models").Sub("modelA")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.