「这是我参与2022首次更文挑战的第21天,活动详情查看:2022首次更文挑战」
前言
Viper是适用于Go应用程序(包括
Twelve-Factor App)的完整配置解决方案。它被设计用于在应用程序中工作,并且可以处理所有类型的配置需求和格式。
viper特点
- 设置默认值
- 从
JSON、TOML、YAML、HCL、envfile和Java properties格式的配置文件读取配置信息 - 实时监控和重新读取配置文件(可选)
- 从环境变量中读取
- 从远程配置系统(etcd或Consul)读取并监控配置变化
- 从命令行参数读取配置
- 从buffer读取配置
- 显式配置值
viper使用
首先在go.mod文件中引入
github.com/spf13/viper v1.7.1
在代码引入
import "github.com/spf13/viper"
如果go.mod没引入成功,则同时在代码里加上import先,在继续go mod vendor引入。
新建一个配置文件config.json
{ "log_level": "INFO",
"server_port": 8080,
"mysql_db_ip": "10.252.79.16",
"mysql_db_port": 7777,
"mysql_db_database": "jc_user",
"mysql_db_user": "root",
"mysql_db_password": "123456",
"mysql_db_max_idle": 10,
"mysql_db_max_open": 10,
"mysql_db_show_sql": true,
"redis_ip": "127.0.0.1",
"redis_port": 8088,
"redis_password": "123456"}
如上配置一些我们需要动态配置的一些参数,根据自己需要配置,我这里配置的是数据库的一些配置、redis的配置。
初始化代码
func InitConfig() {
//设置默认值
viper.SetDefault("log_level", "INFO")
viper.SetDefault("server_port", 8080)
viper.SetDefault("mysql_db_ip", "127.0.0.1")
viper.SetDefault("mysql_db_port", 3306)
viper.SetDefault("mysql_db_database", "defaultdb")
viper.SetDefault("mysql_db_user", "root")
viper.SetDefault("mysql_db_password", "123456")
viper.SetDefault("mysql_db_max_idle", 10)
viper.SetDefault("mysql_db_max_open", 10)
viper.SetDefault("mysql_db_show_sql", true)
viper.SetDefault("mongo_cluster_uri", "mongodb://127.0.0.1:27017")
viper.SetDefault("mongo_database", "defaultdb")
viper.SetDefault("mongo_connect_timeout", "30s")
viper.SetDefault("redis_ip", "127.0.0.1")
viper.SetDefault("redis_port", 6379)
viper.SetDefault("redis_password", "123456")
//设置config.json
viper.SetConfigName("config")
// name of config file (without extension)
viper.SetConfigType("json")
// REQUIRED if the config file does not have the extension in the name
viper.AddConfigPath("/etc/jun-porcelain/") // path to look for the config file in
viper.AddConfigPath("$HOME/.jun-porcelain") // call multiple times to add many search paths
viper.AddConfigPath(".") // optionally look for config in the working directory
//设置env
viper.SetEnvPrefix("jc")
viper.AutomaticEnv()
//读配置 env > json > defalt
err := viper.ReadInConfig() // Find and read the config file
//监听配置文件变化,自动热加载
viper.WatchConfig()
if err != nil {
fmt.Printf("Fatal read config: %s \n", err)
} //初始化 err = viper.Unmarshal(&cfg)
if err != nil {
fmt.Printf("Fatal unmarshal config json: %s \n", err)
}}
方法介绍
SetDefault 设置默认的参数默认值,填入(key,value)既可,不过默认值是优先级最低的。如果配置文件或环境变量有 相同key,默认值就会失效。
SetConfigName 设置配置的文件名
SetConfigType 设置配置的文件名类型
AddConfigPath 定义配置的文件路径,可以设置多个ConfigPath,按顺序查找,如果第一个没有,就去第二个,然后到第三个。
SetEnvPrefix 设置环境变量
ReadInConfig 读取配置文件
WatchConfig 监听配置文件变化,自动热加载
AutomaticEnv 自动检查env环境变量
Unmarshal 将viper读取到的值序列化成对象
运行代码读取看到日志如下
看到这些日志都是从我们的配置文件里读取到了,并且序列化到了我们的对象里,在全局上下文里都能获取到,就可以根据需要使用了。
总结
viper是一个很方便的读取配置文件库。Viper会按照下面的优先级。每个项目的优先级都高于它下面的项目:
- 显示调用
Set设置值 - 命令行参数(flag)
- 环境变量
- 配置文件
- key/value存储
- 默认值
所以根据情况使用对应的配置。