spf13/viper

2021-12-26  本文已影响0人  JunChow520

参考资料

Viper(毒蛇,蝰蛇)是Golang应用程序开源配置解决方案,包括12-Factor应用程序。旨在应用程序中处理各种类型的配置需求和格式。Vipper又被认为是应用程序配置需求的"注册表"。

Viper配置解决方案

安装Viper包

$ go get -u https://github.com/spf13/viper

实例化 viper.New

v := viper.New()

设置参数 SetConfigXxx

func (v *Viper) SetConfigName(in string) //设置配置文件名称
func (v *Viper) SetConfigFile(in string) //设置配置文件路径
func (v *Viper) SetConfigType(in string) //设置配置文件类型

例如:

v.SetConfigName(configName) 
v.SetConfigFile(configFile) 
v.SetConfigType(configType) 

读取配置 ReadInConfig

func (v *Viper) ReadInConfig() error

例如:

//读取配置文件
err := v.ReadInConfig()
if err != nil {
    panic(fmt.Errorf("Fatal error config file: %s \n", err))
}

Viper读取配置顺序

顺序 类型 描述
1 explict call to Set 设置显式调用,读取viper.Set()设置的值。
2 flag 命令行标志,从命令行读取配置。
3 env 操作系统环境变量,从环境变量读取配置。
4 config 配置文件,监控配置文件改动并热加载。
5 key/value store 远程键值存储,从远程配置中心读取配置并监控变动。
6 default 默认值,直接设置配置项值。
// 获取配置文件路径
func getConfigFile(path ...string) string {
    //从入参获取
    if len(path) > 0 {
        return path[0]
    }
    //命令行标记
    var p string
    flag.StringVar(&p, "c", "", "choose config file.")
    flag.Parse()
    if p != "" {
        return p
    }
    //操作系统环境变量
    p = os.Getenv("CONFIG_HOME")
    if p != "" {
        return p
    }
    //默认值
    return "config.yaml"
}

监控配置 WatchConfig

func (v *Viper) WatchConfig()
func (v *Viper) OnConfigChange(run func(in fsnotify.Event))

例如:

//监控配置并获取最新配置
v.WatchConfig()

//配置文件修改时触发并解析
v.OnConfigChange(func(e fsnotify.Event) {
    fmt.Println("config file changed:", e.Name)
    if err := v.Unmarshal(&config.Cfg); err != nil {
        fmt.Println(err)
    }
})

例如:读取YAML配置并实时监听改动

// 解析配置文件
func Viper(path ...string) *viper.Viper {
    //获取配置文件路径
    configFile := getConfigFile()
    fmt.Printf("Vipper Config File is %v\n", configFile)

    //实例化
    v := viper.New()
    v.SetConfigFile(configFile)        //设置配置文件路径
    v.SetConfigType(config.ConfigType) //设置配置文件类型

    //读取配置文件
    err := v.ReadInConfig()
    if err != nil {
        panic(fmt.Errorf("Fatal error config file: %s \n", err))
    }

    //监控配置并获取最新配置
    v.WatchConfig()
    //配置文件修改时触发并解析
    v.OnConfigChange(func(e fsnotify.Event) {
        fmt.Println("config file changed:", e.Name)
        if err := v.Unmarshal(&config.Cfg); err != nil {
            fmt.Println(err)
        }
    })

    //解析全局配置
    if err := v.Unmarshal(&config.Cfg); err != nil {
        fmt.Println(err)
    }

    return v
}
上一篇 下一篇

猜你喜欢

热点阅读