Advanced setup with golang Viper lib

I am working on my first real Go project and have been looking for some tools to handle configuration.

Finally, I found this tool: https://github.com/spf13/viper , which is really good, but I have some problems when I try to handle 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 do not know how to get values ​​from modelB, for example. Looking at the lib code, I found the following, but I really don't 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 all sides, to do something like this in my package:

 modelsConf := viper.Get("models") fmt.Println(modelsConf["modelA"]["varA"]) 

Can someone explain to me the best way to achieve this?

+5
source share
2 answers

Since the "models" block is a map, it is a little easier to call.

 m := viper.GetStringMap("models") 

m will be the interface map [string] {}

Then you get the value m [key], which is the interface {}, so you drop it to map the interface [interface {}] {}:

 m := v.GetStringMap("models") mm := m["modelA"].(map[interface{}]interface{}) 

Now you can access the "varA" key by passing the key as an interface {}:

 mmm := mm[string("varA")] 

mmm - foo

+7
source

You can simply use:

m := viper.Get("models.modelA")

or

newViperForModelA := viper.Sub("models").Sub("modelA")

0
source

Source: https://habr.com/ru/post/1207661/


All Articles