项目地址https://github.com/spf13/viper
1. viper
viper读取配置信息的优先级顺序,从高到底:
- 显式调用Set函数
- 命令行参数
- 环境变量
- 配置文件
- key/value存储系统
- 默认值
2. 设置值
(1)设置默认值
viper.SetDefault("ContentDir", "content")
...
(2)读取配置文件
viper.SetConfigName("xxx") // 设置配置文件名,不要带后缀
viper.AddConfigPath("/path") // 第一个搜索路径
viper.AddConfigPath("../etc") // 设置为相对路径
err := viper.ReadInConfig() // 搜索路径,并读取配置数据
(3)***监视配置文件
viper支持应用程序运行时拥有读取配置文件的能力
viper实例通过WatchConfig函数:
viper.WatchConfig()
viper.OnConfigChange(func(e fsnotify.Event)) {
fmt.Println("Config file changed:", e.Name)
})
(4)Set调用
viper.Set("Verbose", true)
viper.Set("LogFile", LogFile)
(5)绑定命令行参数
***viper支持绑定pflags参数【pflags是一个命令行参数解析库】
serveCmd.Flags().Int("port", 1138, "Port to run Application server on")
viper.BindPFlag("port", serverCmd.Flags().Lookup("port"))
3. 获取值
- Get(key string) : interface{}
- GetBool(key string) : bool
- GetFloat64(key string) : float64
- GetInt(key string) : int
- GetString(key string) : string
- GetStringMap(key string) : map[string]interface{}
- GetStringMapString(key string) : map[string]string
- GetStringSlice(key string) : []string
- GetTime(key string) : time.Time
- GetDuration(key string) : time.Duration
- IsSet(key string) : bool