dqifn68206 2014-11-25 11:19
浏览 218
已采纳

使用golang Viper lib进行高级配置

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?

  • 写回答

2条回答 默认 最新

  • doupuchen6378 2015-03-25 09:28
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料