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"`
}

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

相关推荐
花酒锄作田7 天前
Gin 框架中的规范响应格式设计与实现
golang·gin
qwfys2007 天前
How to install golang 1.26.0 to Ubuntu 24.04
ubuntu·golang·install
codeejun7 天前
每日一Go-25、Go语言进阶:深入并发模式1
开发语言·后端·golang
石牌桥网管7 天前
Go 泛型(Generics)
服务器·开发语言·golang
小二·7 天前
Go 语言系统编程与云原生开发实战(第21篇)
开发语言·云原生·golang
小二·7 天前
Go 语言系统编程与云原生开发实战(第20篇)
开发语言·云原生·golang
女王大人万岁7 天前
Golang实战Eclipse Paho MQTT库:MQTT通信全解析
服务器·开发语言·后端·golang
codeejun7 天前
每日一Go-24、Go语言实战-综合项目:规划与搭建
开发语言·后端·golang
石牌桥网管7 天前
Go类型断言
开发语言·后端·golang
普通网友8 天前
PHP语言的正则表达式
开发语言·后端·golang