简介
viper 是一个配置解决方案,拥有丰富的特性:
- 支持 JSON/TOML/YAML/HCL/envfile/Java properties 等多种格式的配置文件;
- 可以设置监听配置文件的修改,修改时自动加载新的配置;
- 从环境变量、命令行选项和io.Reader中读取配置;
- 从远程配置系统中读取和监听修改,如 etcd/Consul;
- 代码逻辑中显示设置键值。
获取
$ go get github.com/spf13/viper
读取配置
viper读入配置有如下读入方式:
- 设置默认的配置名
- 读取配置文件
- 监听和重新读取配置文件
- 从io.Reader读取配置
- 从环境变量读取
- 从命令行标志读取
- 从远程Key/Value存储读取
读取顺序
- 从默认的设置中读取
- 从pflag中读取
- 从环境变量中读取
- 从配置文件中读取
- 从KV存储中读取
- 从默认的配置文件中读取
其API如下,这里我将其进行分组
AddConfigPath
func AddConfigPath(in string)
添加文件的搜索路径
AddRemoteProvider
func AddRemoteProvider(provider, endpoint, path string) error
添加远程源,当前支持etcd、consul、firestore
- provider:etcd、consul、firestore
- endpoint:连接地址
- etcd为http://ip:port
- consul为ip:port
- path从kv存储中检索配置的路径,例如要从/configs/myapp.json检索名为myapp.json的配置文件则应该设置为/config并将配置名(SetConfigName)设置为myapp
** **AddSecureRemoteProvider
func AddSecureRemoteProvider(provider, endpoint, path, secretkeyring string) error
添加远程源,当前支持etcd、consul、firestore
- provider:etcd、consul、firestore
- endpoint:连接地址
- etcd为http://ip:port
- consul为ip:port
- path从kv存储中检索配置的路径,例如要从/configs/myapp.json检索名为myapp.json的配置文件则应该设置为/config并将配置名(SetConfigName)设置为myapp
- secretkeyring:密钥路径
AllKeys
func AllKeys() []string
返回所有的键。
AllSettings
func AllSettings() map[string]interface{}
将所有键值对返回
AllowEmptyEnv
func AllowEmptyEnv(allowEmptyEnv bool)
是否允许空的环境变量视为有效值,默认是false
AutomaticEnv
func AutomaticEnv()
开启环境变量检查是否匹配现有键值,如果匹配则加载。
BindEnv
func BindEnv(input ...string) error
将环境变量的值设置到viper键中,该函数可以提供一或两个参数。
- 只提供一个参数: 默认环境变量与该简直名称相同。
- 提供两个参数:第一个参数是键,第二个参数是环境变量名称。
例如:
//假设配置文件中设置了值为192.168.3.244
fmt.Println(viper.GetString("mysql.ip")) // 192.168.3.244
// 绑定环境变量,假设我们设置mysql.ip=127.0.0.1、MYSQL.IP=localhost
viper.BindEnv("mysql.ip")//127.0.0.1是调用os.LookupEnv获取的值
fmt.Println(viper.GetString("mysql.ip"))
BindFlagValue
func BindFlagValue(key string, flag FlagValue) error
将键同flag绑定
BindFlagValues
func BindFlagValues(flags FlagValueSet) error
绑定flag集合
BindPFlag
func BindPFlag(key string, flag \*pflag.Flag) error
绑定pflag
BindPFlags
func BindPFlags(flags \*pflag.FlagSet) error
绑定pflag集合
ConfigFileUsed
func ConfigFileUsed() string
返回正在使用的配置文件,例如:
D:\workspace\myOpenSource\go-example\viper\ini\config.ini
Debug
func Debug()
打印调试信息,会根据viper查找顺序打印配置信息。例如:
Aliases:
map[string]string{}
Override:
map[string]interface {}{}
PFlags:
map[string]viper.FlagValue{}
Env:
map[string][]string{}
Key/Value Store:
map[string]interface {}{}
Config:
map[string]interface {}{"mysql.database":"awesome", "mysql.ip":"127.0.0.1", "mysql.password":"123456", "mysql.port":"3306", "mysql.user":"dj", "redis.ip":"127.0.0.1", "redis.port":"7381"}
Defaults:
map[string]interface {}{}
Get
获取指定key值信息
func Get(key string) interface{}
func GetBool(key string) bool
func GetDuration(key string) time.Duration
func GetFloat64(key string) float64
func GetInt(key string) int
func GetInt32(key string) int32
func GetInt64(key string) int64
func GetIntSlice(key string) []int
func GetSizeInBytes(key string) uint
func GetString(key string) string
func GetStringMap(key string) map[string]interface{}
func GetStringMapString(key string) map[string]string
func GetStringMapStringSlice(key string) map[string][]string
func GetStringSlice(key string) []string
func GetTime(key string) time.Time
func GetUint(key string) uint
func GetUint32(key string) uint32
func GetUint64(key string) uint64
InConfig
func InConfig(key string) bool
判断这个键是否存在。
fmt.Println(viper.InConfig("mysql")) //false
fmt.Println(viper.InConfig("ip")) //false
fmt.Println(viper.InConfig("mysql.ip")) //true
InSet
func IsSet(key string) bool
判断键是否是个集合
MergeConfig
func MergeConfig(in io.Reader) error
func MergeConfigMap(cfg map[string]interface{}) error
func MergeInConfig() error
会将新的配置和原有的配置合并
OnConfigChang
func OnConfigChange(run func(in fsnotify.Event))
设置配置改变时的回调函数
ReadConfig
func ReadConfig(in io.Reader) error
从IO接口中读取配置
ReadInConfig
func ReadInConfig() error
加载配置文件
ReadRemoteConfig
func ReadRemoteConfig() error
加载远程配置文件
RegisterAlias
func RegisterAlias(alias string, key string)
为key设置一个别名。
Reset
func Reset()
将存储的所有信息清空,仅用于测试
SafeWriteConfig
func SafeWriteConfig() error
仅当文件不存在时,将当前配置写入文件
SafeWriteConfigAs
func SafeWriteConfigAs(filename string) error
将当前配置写入给定文件名(如果它不存在)。
Set
func Set(key string, value interface{})
覆盖内存中的键的值,对键不区分大小写。将用于代替通过flag、配置文件、环境变量、默认值或键/值存储获得的值。
SetConfigFile
func SetConfigFile(in string)
明确定义配置文件的路径、名称和扩展名。Viper 将使用它而不检查任何配置路径。
SetConfigName
func SetConfigName(in string)
设置配置文件的名称。不包括扩展名。
SetConfigPermissions
func SetConfigPermissions(perm os.FileMode)
设置给定配置文件的权限
SetConfigType
func SetConfigType(in string)
设置配置文件的类型,如json、ini、toml
SetDefault
func SetDefault(key string, value interface{})
为指定的键设置默认值,对key不区分大小写,仅当用户没有通过flag、配置文件以及环境变量设置值时才使用默认值。
SetEnvKeyReplacer
func SetEnvKeyReplacer(r \*strings.Replacer)
允许你使用一个strings.Replacer对象来将配置名重写为Env名。如果你想在Get()中使用包含-的配置名 ,但希望对应的环境变量名包含_分隔符,就可以使用该方法。使用它的一个例子可以在项目中viper_test.go文件里找到。
func TestSetEnvKeyReplacer(t \*testing.T) {
Reset()
AutomaticEnv()
testutil.Setenv(t, "REFRESH\_INTERVAL", "30s")
replacer := strings.NewReplacer("-", "\_")
SetEnvKeyReplacer(replacer)
assert.Equal(t, "30s", Get("refresh-interval"))
}
SetEnvPrefix
func SetEnvPrefix(in string)