在咱们开发过程当中,像数据库信息、邮件配置和其余的第三方服务密钥等这些固定的信息都会写在配置文件中,而配置文件又有多种表现形式和格式,有 JSON, TOML, YAML各类格式,并且测试环境,开发环境和生产环境用的配置文件也不是同一份,那就让咱们说说Go 中用于加载配置信息的Viper。git
Viper是Go应用程序的完整配置解决方案,包括12-Factor应用程序。它旨在在应用程序中工做,并能够处理全部类型的配置需求和格式。它支持:github
Viper能够被认为是全部应用程序配置需求的注册表。数据库
在构建现代应用程序时,您没必要担忧配置文件格式; 你能够专一于构建出色的软件。 Viper 能够作以下工做:json
Viper读取配置信息的优先级顺序,从高到低,以下:bash
使用 go get -u github.com/spf13/viper 进行安装ide
const (
// gRPC 服务地址
Address = "0.0.0.0:9090"
)
......
复制代码
像上面这种地址写死在代码里,咱们能够把它放入配置文件中进行读取,安装完viper后,利用viper写toml格式的文件函数
func init(){
viper.SetConfigFile("hello.toml")//文件名
viper.Set("Address","0.0.0.0:9090")//统一把Key处理成小写 Address->address
err := viper.WriteConfig()//写入文件
if err != nil { // Handle errors reading the config file
panic(fmt.Errorf("Fatal error config file: %s \n", err))
}
}
复制代码
运行一下,会发现当前目录会出现一个hello.toml的文件✅测试
相对于写入配置文件的操做,读取配置文件在代码中反而会常见得多spa
viper.SetConfigFile("hello.toml")
err := viper.ReadInConfig() // 会查找和读取配置文件
if err != nil { // Handle errors reading the config file
panic(fmt.Errorf("Fatal error config file: %s \n", err))
}
Address = viper.GetString("Address")
//key取Address或者address都能取到值,反正viper转成小写处理
fmt.Println(Address)
复制代码
viper.SetDefault("ContentDir", "content")
viper.SetDefault("LayoutDir", "layouts")
viper.SetDefault("Taxonomies", map[string]string{"tag": "tags", "category": "categories"})
复制代码
viper.WatchConfig()
viper.OnConfigChange(func(e fsnotify.Event) {
fmt.Println("配置发生变动:", e.Name)
})
复制代码
启用该功能,须要导入 viper/remot 包:命令行
import _ "github.com/spf13/viper/remote"
viper.AddRemoteProvider("etcd", "http://127.0.0.1:4001", "/config/hello.json")
viper.SetConfigType("json") // 由于不知道格式,因此须要指定
err := viper.ReadRemoteConfig()
复制代码
如下是所有代码截图
viper代码短小精悍,就三个文件,很是适合初学者阅读,若是有须要,之后会出源码阅读篇。