简体   繁体   English

使用golang Viper lib进行高级配置

[英]Advanced configuration with the golang Viper lib

I'm working on my first real Go project and have been searching for some tools to handle the configuration. 我正在开发我的第一个真正的Go项目,并一直在寻找一些工具来处理配置。

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: 最后,我找到了这个工具: 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"

I don't know how to get the values from modelB for example. 我不知道如何从modelB获取值。 While looking at the lib code, I've found the followings but I don't really understand how to use it: 在查看lib代码时,我发现了以下内容,但我真的不明白如何使用它:

// 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 {} m将是一个map [string] interface {}

Then, you get the value of m[key], which is an interface {}, so you cast it to map[interface {}]interface {} : 然后,你得到m [key]的值,它是一个接口{},所以你把它转换为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 {} : 现在,您可以访问“varA”键,将密钥作为接口{}传递:

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

mmm is foo 嗯是foo

You can simply use: 你可以简单地使用:

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

or 要么

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM