Golang項目的配置管理——Viper簡易入門配置
What is Viper?
From:https://github.com/spf13/viper
Viper is a complete configuration solution for Go applications including 12-Factor apps.
(VIPER是實現遵循12-Factor的GO應用程序的完整配置解決方案)
它支持:
支持 JSON/TOML/YAML/HCL/envfile/Java properties 等多種格式的配置文件
實時監控及重載配置文件(可選)
從環境變量、命令行標記、緩存中讀取配置;
從遠程配置系統中讀取和監聽修改,如 etcd/Consul;
顯式設置鍵值。
Why Viper?
When building a modern application, you don’t want to worry about configuration file formats; you want to focus on building awesome software. Viper is here to help with that.
(構建現代應用程序時,你不想去過多關注配置文件的格式,你想專注於建立更棒的軟件,Viper可以幫助你)
Install
go get github.com/spf13/viper
Example
初始化:
package settings
import (
"fmt"
"github.com/fsnotify/fsnotify"
"github.com/spf13/viper"
)
//初始化一個viper配置
func Init() (err error) {
//制定配置文件的路徑
viper.SetConfigFile("conf/config.yaml")
// 讀取配置信息
err = viper.ReadInConfig()
if err != nil {
// 讀取配置信息失敗
fmt.Printf("viper.ReadInConfig()failed,err:%v\n", err)
return
}
//監聽修改
viper.WatchConfig()
//為配置修改增加一個回調函數
viper.OnConfigChange(func(in fsnotify.Event) {
fmt.Println("配置文件修改了...")
})
return
}
配置文件示例(yaml):
mysql:
host: "127.0.0.1"
port: 3306
user: "root"
password: "123456"
dbname: "web_app"
max_open_conns: 200
max_idle_conns: 50
redis:
host: "127.0.0.1"
port: 6379
db: 0
password: ""
pool_size: 100
取配置:
package mysql
//省略package
func Init() (err error) {
dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True",
viper.GetString("mysql.user"),
viper.GetString("mysql.password"),
viper.GetString("mysql.host"),
viper.GetInt("mysql.port"),
viper.GetString("mysql.dbname"),
)
db, err = sqlx.Connect("mysql", dsn)
db.SetMaxOpenConns(viper.GetInt("mysql.max_open_conns"))
db.SetMaxIdleConns(viper.GetInt("mysql.max_idle_conns"))
return
}
// @version 1.0
程序內顯示聲明配置:
如果某個鍵通過viper.Set
設置了值,那么這個值的優先級最高。如:
viper.Set("redis.port", 9000)
此時redis的接口就不是配置文件中設置的6379,而是后面配置的9000
命令行選項:
func init() {
pflag.Int("redis.port", 9001, "Redis port to connect")
// 綁定命令行
viper.BindPFlags(pflag.CommandLine)
}
代碼運行時傳入參數:$ ./main.exe --redis.port 9001
此時程序配置的redis端口為:9001。
如果我們不傳入參數直接執行$ ./main.exe
此時程序配置的redis端口為配置文件中的6379(沒有在程序中顯示聲明配置時viper.Set("redis.port", 9000)
)。
環境變量:
func init() {
// 綁定環境變量
viper.AutomaticEnv()
}
在沒有於前面的方法中取得配置的情況下,則會綁定環境變量。
也可以指定綁定對應的環境變量:
func init() {
// 綁定環境變量
viper.BindEnv("redis.port")
viper.BindEnv("go.path", "GOPATH")
}
BindEnv()
如果只傳入一個參數,則這個參數既表示鍵名,又表示環境變量名。如果傳入兩個參數,則第一個參數表示鍵名,第二個參數表示環境變量名。
也可以通過viper.SetEnvPrefix()
設置環境變量前綴,設置后前面的方法會為傳入的值加上變量后再去查找環境變量。
- 默認值可以調用
viper.SetDefault
設置。
總結優先級:
調用Set
顯式設置的>命令行選項傳入的>環境變量>配置文件>默認值;
總結
初始化:
- 設置配置文件路徑
viper.SetConfigFile()
- 讀取配置
viper.ReadInConfig()
- 監聽修改
viper.WatchConfig()
- 設置修改后回調
viper.OnConfigChange(func())
調用:
取配置viper.Get*()
設置優先級:
聲明調用Set
顯式設置的>命令行選項傳入的>環境變量>配置文件>默認值;
我的個人站:mrxuexi.com