viper是什么?
解决程序相关配置,支持多种文件格式,方便快捷,简化配置过程,易修改配置参数
- 默认配置
- 从 JSON, TOML, YAML, HCL 和 Java 属性配置文件读取数据
- 实时查看和重新读取配置文件(可选)
- 从环境变量中读取
- 从远程配置系统(etcd 或 Consul)读取数据并监听变化
- 从命令行参数读取
- 从 buffer 中读取
- 设置显式值
快速上手
终端引入viper依赖
go get github.com/spf13/viper
常用方法:
viper.SetConfigFile("haha") //配置文件名,不需要后缀 viper.SetConfigType("yaml") //设置配置文件格式 viper.AddConfigPath("../config") //查找路径 err := viper.ReadInConfig() //读取配置文件 if err != nil { panic(fmt.Errorf("fail to find config,please revise it (viper/config)")) } //监听配置文件,当配置文件改变的时候,不需要重新启动 viper.OnConfigChange(func(e fsnotify.Event) { fmt.Println("Config file changed:", e.Name) })
对应go中的mysql写法
mysql: host: 127.0.0.1 port: 3306 username: xxxx password: xxxx method: tcp database: xxxx config: charset=utf8mb4&parseTime=True&loc=Local
注意点:
接收的结构体内部需要跟yaml的字段进行绑定;
默认情况下,mapstructure使用结构体中字段的名称做这个映射
type Mysql struct { Host string `mapstructure:"host"` Port string `mapstructure:"port"` Username string `mapstructure:"username"` Password string `mapstructure:"password"` Method string `mapstructure:"method"` Database string `mapstructure:"database"` Config string `mapstructure:"config"` }
官方文档:
https://geekdaxue.co/read/go-packages-docs-awesome/docs-viper-README.md