我是新手,我正在使用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的简单代码:
package main
import (
"fmt"
"gopkg.in/yaml.v2"
"log"
)
var data = `
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
`
func main() {
m := make(map[interface{}]interface{})
err := yaml.Unmarshal([]byte(data), &m)
if err != nil {
log.Fatalf("error: %v", err)
}
fmt.Printf("%vn", m)
}
如果您希望将yaml
结构映射到严格的 golang struct
您可以使用 mapstructure 库来映射每个国家/地区下的嵌套键/值对。
例如:
package main
import (
"github.com/spf13/viper"
"github.com/mitchellh/mapstructure"
"fmt"
"log"
)
type CountryConfig struct {
Qtype string
Qplacetype string
}
type QueryConfig struct {
CountryQueries map[string][]CountryConfig;
}
func NewQueryConfig () QueryConfig {
queryConfig := QueryConfig{}
queryConfig.CountryQueries = map[string][]CountryConfig{}
return queryConfig
}
func main() {
viper.SetConfigName("test")
viper.AddConfigPath(".")
err := viper.ReadInConfig()
queryConfig := NewQueryConfig()
if err != nil {
log.Panic("error:", err)
} else {
mapstructure.Decode(viper.AllSettings(), &queryConfig)
}
for _, config := range queryConfig.CountryQueries["sg"] {
fmt.Println("qtype:", config.Qtype, "qplacetype:", config.Qplacetype)
}
}
此包 https://github.com/go-yaml/yaml 在 Go 中序列化/反序列化 YAML。