Golang項目的配置管理——Viper簡易入門配置

Golang項目的配置管理——Viper簡易入門配置

What is Viper?

From://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顯式設置的>命令行選項傳入的>環境變數>配置文件>默認值;

總結

初始化:

  1. 設置配置文件路徑viper.SetConfigFile()
  2. 讀取配置viper.ReadInConfig()
  3. 監聽修改viper.WatchConfig()
  4. 設置修改後回調viper.OnConfigChange(func())

調用:

​ 取配置viper.Get*()

設置優先順序:

聲明調用Set顯式設置的>命令行選項傳入的>環境變數>配置文件>默認值;

我的個人站:mrxuexi.com

頭像