使用golang Viper lib进行高级配置

Ced*_*ent 5 yaml config go

我正在开发我的第一个真正的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"
Run Code Online (Sandbox Code Playgroud)

我不知道如何从modelB获取值.在查看lib代码时,我发现了以下内容,但我真的不明白如何使用它:

// Marshals the config into a Struct
func Marshal(rawVal interface{}) error {...}

func AllSettings() map[string]interface{} {...}
Run Code Online (Sandbox Code Playgroud)

我想要的是能够从我的包装中的任何地方做一些类似的事情:

modelsConf := viper.Get("models")
fmt.Println(modelsConf["modelA"]["varA"])
Run Code Online (Sandbox Code Playgroud)

能有人向我解释实现这一目标的最佳方法吗?

Ste*_*oux 8

由于"模型"块是一个地图,因此调用起来要容易一些

m := viper.GetStringMap("models")
Run Code Online (Sandbox Code Playgroud)

m将是一个map [string] interface {}

然后,你得到m [key]的值,它是一个接口{},所以你把它转换为map [interface {}] interface {}:

m := v.GetStringMap("models")
mm := m["modelA"].(map[interface{}]interface{})
Run Code Online (Sandbox Code Playgroud)

现在,您可以访问"varA"键,将密钥作为接口{}传递:

mmm := mm[string("varA")]
Run Code Online (Sandbox Code Playgroud)

嗯是foo