一個強大簡單好用的配置解決方案,Vipergit
Viper具備如下特性:github
Viper的讀取順序:緩存
viper.Set()
所設置的值Viper在初始化以後,只須要調用viper.GetString()
、viper.GetInt()
和 viper.GetBool()
等函數便可獲得配置文件中對應的參數。微信
Viper 也能夠很是方便地讀取多個層級的配置,好比這樣一個 YAML 格式的配置:函數
common:
db:
name: db
addr: 127.0.0.1:3306
username: root
password: root
複製代碼
若是要讀取name,只須要執行viper.GetString("common.db.name")
就能夠ui
下面來一個簡單的例子介紹Viper: config/config.go
spa
package config
import (
"strings"
"github.com/fsnotify/fsnotify"
"github.com/spf13/viper"
)
type Config struct {
Name string
}
func Init(cfg string) error {
c := Config{
Name: cfg,
}
// 初始化配置文件
if err := c.initConfig(); err != nil {
return err
}
c.watchConfig()
return nil
}
func (c *Config) initConfig() error {
if c.Name != "" {
// 若是指定了配置文件,則解析指定的配置文件
viper.SetConfigFile(c.Name)
} else {
// 若是沒有指定配置文件,則解析默認的配置文件
viper.AddConfigPath("conf")
viper.SetConfigName("config")
}
// 設置配置文件格式爲YAML
viper.SetConfigType("yaml")
// viper解析配置文件
if err := viper.ReadInConfig(); err != nil {
return err
}
return nil
}
// 監聽配置文件是否改變,用於熱更新
func (c *Config) watchConfig() {
viper.WatchConfig()
viper.OnConfigChange(func(e fsnotify.Event) {
fmt.Printf("Config file changed: %s\n", e.Name)
})
}
複製代碼
conf/config.yaml
命令行
name: demo
common:
db:
name: db
addr: 127.0.0.1:3306
username: root
password: root
複製代碼
main.go
code
package main
import (
"test/config"
"fmt"
"github.com/spf13/viper"
)
func main() {
if err := config.Init(""); err != nil {
panic(err)
}
name := viper.GetString("name")
fmt.Println("Viper get name:",name)
}
複製代碼
執行go run main.go
cdn
輸出Viper get name: demo
微信搜索「goentry-xyz」,關注公衆號「燈下獨碼」