go - 将嵌套配置 Yaml 映射到结构

标签 go struct config viper-go

我是新来的,我正在使用 viper 加载我所有的配置,我目前拥有的是如下所示的 YAML

 countryQueries:
  sg:
    - qtype: gmap
      qplacetype: postal_code
    - qtype: gmap
      qplacetype: address
    - qtype: geocode
      qplacetype: street_address

  hk:
    - qtype: gmap
      qplacetype: postal_code
    - qtype: gmap
      qplacetype: address
    - qtype: geocode
      qplacetype: street_address

请注意,国家代码是动态的,可以随时为任何国家添加。那么我如何将其映射到技术上我可以做的结构

for _, query := range countryQueries["sg"] { }

我尝试通过循环来自己构造它,但我卡在这里了

for country, queries := range viper.GetStringMap("countryQueries") {
    // i cant seem to do anything with queries, which i wish to loop it
    for _,query := range queries {} //here error
}

最佳答案

读完一些书后意识到 viper 有自己的解码功能,效果很好 https://github.com/spf13/viper#unmarshaling

这就是我所做的

type Configuration struct {
    Countries map[string][]CountryQuery `mapstructure:"countryQueries"`
}

type CountryQuery struct {
    QType      string
    QPlaceType string
}

func BuildConfig() {
    viper.SetConfigName("configFileName")
    viper.AddConfigPath("./config")
    err := viper.ReadInConfig()
    if err != nil {
        panic(fmt.Errorf("Error config file: %s \n", err))
    }

    var config Configuration

    err = viper.Unmarshal(&config)
    if err != nil {
        panic(fmt.Errorf("Unable to decode Config: %s \n", err))
    }
}

关于go - 将嵌套配置 Yaml 映射到结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41631008/

相关文章:

c - 我是否在我的结构指针上正确地调用了 free() ?

c# - 找不到 ASP.NET 服务使用的动态加载的第 3 方程序集的 .config 文件

javascript - 在 config.js 文件中需要 baseurl

JSON unmarshal 不在我的代码中输出,在 goplayground 中工作

go - 被调用的 Go 包中的全局变量

c - 指向结构体指针的指针

c++ - 结构前向声明编译失败

config - 如何获取 bundle 配置以使用多个构建选项?

go - 我如何使用 Atom.io 让 go-plus 知道我正在服务器上开发?

go - 有没有一种直接的方法可以用多键排序并插入 Golang 中的 slice ?