一个强大简单好用的配置解决方案,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」,关注公众号「灯下独码」