我从其他地方读取配置,它返回一个映射并且所有值都是字符串,并且不确定 Config.Mp 映射中的哪个键,所以我想这样做,但是在 Unmarshal 之后 Mp 为零,我怎么能用好方法吗?钩子什么的?谢谢~
type DB struct {
Name string `mapstructure:"name"`
Ip string `mapstructure:"ip"`
Vars []string `mapstructure:"vars"`
}
type Config struct {
Aid string `mapstructure:"aid"`
Times int `mapstructure:"times"`
Mp map[string]interface{} `mapstructure:"mp"`
DBConfig DB `mapstructure:"db"`
}
func map2Struct() {
m := make(map[string]interface{})
m["aid"] = "123"
m["db.name"] = "test"
m["db.ip"] = "10.0.0.2"
m["db.vars"] = `a, b`
m["times"] = "1"
m["mp"] = `{"a": 1, "b": 0.1, "c": "asd", d:[1,2]}`
v := viper.New()
v.MergeConfigMap(m)
v.SetConfigType("properties")
config := Config{}
v.Unmarshal(&config)
}