本文介绍了将嵌套的配置Yaml映射到结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新手,我使用viper会加载我的所有配置,目前我所拥有的YAML外观如下

Im new to go, and im using viper do load all my config what currently i have is the YAML look like below

 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

请注意,国家/地区代码是动态的,可以在任何国家/地区随时添加.那么,如何将其映射到从技术上讲我可以做到的结构

to note that the countrycode are dynamic it could be added anytime for any countries. So how do i map this to a struct where technically speaking i can do

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

我尝试通过循环构建它自己,但我被卡在这里

i try to contruct it myself by looping it but im stucked here

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
}

任何帮助将不胜感激

推荐答案

经过阅读后,发现vi蛇具有其自身的编组功能,可以很好地发挥作用 https://github.com/spf13/viper#unmarshaling

After done some reading realized that viper has it own unmarshaling capabilities which works great 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))
    }
}

这篇关于将嵌套的配置Yaml映射到结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-15 19:12