Viper反序列化解析字段不成功问题

问题背景

通过viper解析文件内容映射config一直失败,相关代码如下

type Config struct {
	DBConf    *DBConf    `toml:"db"`
	RedisConf *RedisConf `toml:"redis"`
	WebConfig *WebConfig `toml:"app"`
}

type DBConf struct {
	Read struct {
		Dsn string `toml:"dsn"` // 最高优先级
	} `toml:"read"`
	Write struct {
		Dsn string `toml:"dsn"` // 最高优先级
	} `toml:"write"`
	Base struct {
		Type            string        `toml:"type"`
		MaxOpenConn     int           `toml:"maxOpenConn"`
		MaxIdleConn     int           `toml:"maxIdleConn"`
		ConnMaxLifeTime time.Duration `toml:"connMaxLifeTime"`
	} `toml:"base"`
}

type CacheType string

type RedisConf struct {
	Address  string `toml:"addr"`
	DB       string `toml:"db"`
	Password string `toml:"password"`
}

type WebConfig struct {
	Port        string `toml:"port"`
	IsDebug     bool   `toml:"debug"`
	LogFilePath string `toml:"path"`
}
	appFullPath := "./conf/" + filePath
	// 解析 config
	viper.SetConfigName("web")
	viper.AddConfigPath(appFullPath)
	viper.SetConfigType("yaml")
	err := viper.ReadInConfig()
	if err != nil {
		log.Fatal("解析文件失败: ", err)
	}
	if err := viper.Unmarshal(&conf); err != nil {
		log.Fatal("解析文件失败: ", err)
	}
	// 监听配置更新
	viper.WatchConfig()
	viper.OnConfigChange(func(e fsnotify.Event) {
		if err := viper.Unmarshal(&conf); err != nil {
			log.Fatal("解析文件失败: ", err)
		}
	})

问题原因

image.png

Viper使用的是 github.com/mitchellh/mapstructure来解析值
mapstructure 用于将通用的map[string]interface{}解码到对应的 Go 结构体中
默认情况下,mapstructure 使用结构体中字段的名称做这个映射,不区分大小写,比如 Name 字段可以映射到
name、NAME、NaMe 等等,如果名称不一致没有指定 tagName ,则默认为 mapstructure,这也是为什么带下划线或者名称不一致的字段不加 mapstructure标签无法解析的原因

解决方案

mapstructure方法

通过mapstructure映射名称

image.png

  • 6
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

每天一个秃顶小技巧

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值