英文:
Advanced configuration with the golang Viper lib
问题
我正在处理我的第一个真正的Go项目,并一直在寻找一些处理配置的工具。
最后,我找到了这个工具:https://github.com/spf13/viper,它非常好用,但是当我尝试处理一些更复杂的配置时,比如下面的config.yaml示例时,我遇到了一些问题:
app:
name: "project-name"
version: 1
models:
modelA:
varA: "foo"
varB: "bar"
modelB:
varA: "baz"
varB: "qux"
varC: "norf"
我不知道如何获取modelB的值。在查看库代码时,我找到了以下内容,但我不太明白如何使用它:
// 将配置转换为结构体
func Marshal(rawVal interface{}) error {...}
func AllSettings() map[string]interface{} {...}
我想要的是能够在我的包的任何地方做类似这样的操作:
modelsConf := viper.Get("models")
fmt.Println(modelsConf["modelA"]["varA"])
有人能解释一下如何实现这个最佳方法吗?
英文:
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?
答案1
得分: 8
由于"models"块是一个映射,所以调用起来比较容易:
m := viper.GetStringMap("models")
m将是一个map[string]interface{}
然后,你可以获取m[key]的值,它是一个interface{},所以你将其转换为map[interface{}]interface{}:
m := v.GetStringMap("models")
mm := m["modelA"].(map[interface{}]interface{})
现在你可以通过将key作为interface{}传递来访问"varA"键:
mmm := mm[string("varA")]
mmm是foo
英文:
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
答案2
得分: 3
你可以简单地使用:
或者
英文:
You can simply use:
or
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论