我是新来的,我正在使用 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/