使用golang Viper库进行高级配置

huangapple go评论99阅读模式
英文:

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

huangapple
  • 本文由 发表于 2014年11月25日 19:19:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/27125244.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定