我是新手,我正在使用 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 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))
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)