问题:
viper读入配置的app.start_time为:start_time=“2020-07-01”(string)
unmarshal到conf结构体中的StartTime(String)字段为空?

且Unmarshal后输出Conf结构体都为类型零值:

结果:

解决方案:
!!!!结构体定义错误!!!!
原来的定义:
type AppConfig struct {
//无论config是什么类型(后缀名称),统一用mapstructure来表示tag
Name string `mapstructure:"name"`
Mode string `mapstructure:"mode"`
Port int `mapdtructure:"port"`
*LogConfig `mapstructure:"log"`
*MysqlConfig `mapstructure:"mysql"`
*RedisConfig `mapstructure:"redis"`
}
解决方案:把AppConfig拆出来,以后访问用:
Conf=new(multipleConfig)
Config.AppConfig.Start_time
var Conf = new(multipleConfig)
type multipleConfig struct {
*AppConfig `mapstructure:"app"`
*LogConfig `mapstructure:"log"`
*MysqlConfig `mapstructure:"mysql"`
*RedisConfig `mapstructure:"redis"`
}
type AppConfig struct {
//无论config是什么类型(后缀名称),统一用mapstructure来表示tag
Name string `mapstructure:"name"`
Mode string `mapstructure:"mode"`
Port int `mapdtructure:"port"`
Version string `mapstructure:"version"`
StartTime string `mapstructure:"start_time"`
MachineId uint16 `mapstructure:"machine_id"`
}
在Go语言中,遇到一个问题:使用viper库读取配置文件时,app.start_time字段无法正确unmarshal到结构体的StartTime字段,导致为空。原因是原始结构体定义不正确。解决方案是将AppConfig结构体从顶级结构体中拆分出来,并在顶级结构体中以指针形式包含它。修复后的结构体使得配置解析正常,能正确获取到start_time字段的值。
12

被折叠的 条评论
为什么被折叠?



