Golang使用viper读取配置到结构体,但是获取的数据为空

1.viper库

viper库是一个读取配置文件的库,支持多种配置文件,如JSON/TOML/YAML/HCL/envfile/Java properties 等

2.遇到的问题

在使用viper库的时候发现按照相应的配置已经读取到了对应的配置,但是转换为结构体的时候发现怎么拿结构体里面的数据都是空的

3. 解决步骤

1.打印所有的viper读取到的配置
yaml 复制代码
database:
  host: 127.0.0.1
  port: 3306
  username: root
  password: root
go 复制代码
fmt.Println(viper.AllSettings())
map[database:map[host:127.0.0.1 password:root port:3306 username:root]]

这个时候发现,他有两层map,这个时候我再加一个配置在yaml里面

yaml 复制代码
database:
  host: 127.0.0.1
  port: 3306
  username: root
  password: root
port: 9000

这个时候去打印发现单个的没有子集的都是只有一个map包裹

go 复制代码
map[database:map[host:127.0.0.1 password:root port:3306 username:root] port:9000]

这个时候port已经可以解析出来了

2.尝试使用一个结构体嵌套一下(解决问题)
go 复制代码
type Global struct {
	Port     int
	Database Database `mapstructure:"database"`
}

type Database struct {
	Host     string `yaml:"host"`
	Port     string `yaml:"port"`
	Username string `yaml:"username"`
	Password string `yaml:"password"`
}

这样就可以将配置转换成对应的结构体了

相关推荐
bianshaopeng6 小时前
ubuntu go 环境变量配置
开发语言·ubuntu·golang
元清加油6 小时前
【Goland】:协程和通道
服务器·开发语言·后端·网络协议·golang
lpfasd1237 小时前
01_Go语言基础与环境搭建
开发语言·后端·golang
xy_recording1 天前
Day08 Go语言学习
开发语言·学习·golang
吧唧霸1 天前
golang读写锁和互斥锁的区别
开发语言·算法·golang
七七&5563 天前
2024年08月13日 Go生态洞察:Go 1.23 发布与全面深度解读
开发语言·网络·golang
java坤坤3 天前
GoLand 项目从 0 到 1:第八天 ——GORM 命名策略陷阱与 Go 项目启动慢问题攻坚
开发语言·后端·golang
元清加油3 天前
【Golang】:函数和包
服务器·开发语言·网络·后端·网络协议·golang
恋喵大鲤鱼3 天前
Golang 后台技术面试套题 1
面试·golang