Fan*_*wan 2 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
Run Code Online (Sandbox Code Playgroud)
请注意,国家/地区代码是动态的,可以随时为任何国家/地区添加。那么我如何将它映射到一个从技术上讲我可以做的结构
for _, query := range countryQueries["sg"] { }
Run Code Online (Sandbox Code Playgroud)
我尝试通过循环来自己构建它,但我卡在这里
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
}
Run Code Online (Sandbox Code Playgroud)
任何帮助都感激不尽
完成一些阅读后意识到毒蛇有自己的解组功能,效果很好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))
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4815 次 |
| 最近记录: |