什么是viper
viper大神spf13编写的开源配置解决方案,viper拥有以下功能以及特性:
1、设置默认值
2、从json、toml yaml、hci和java属性配置文件
3、从环境变量env读取值
4、远程读取配置文件
5、key不区分大小写
举例说明:
1、配置文件如下:
statetransfer:
# Should a replica attempt to fix damaged blocks?
# In general, this should be set to true, setting to false will cause
# the replica to panic, and require a human's intervention to intervene
# and fix the corruption
recoverdamage: true
# The number of blocks to retrieve per sync request
blocksperrequest: 20 # The maximum number of state deltas to attempt to retrieve
# If more than this number of deltas is required to play the state up to date
# then instead the state will be flagged as invalid, and a full copy of the state
# will be retrieved instead
maxdeltas: 200 # Timeouts
timeout:
# How long may returning a single block take
singleblock: 2s
# How long may returning a single state delta take
singlestatedelta: 2s
# How long may transferring the complete state take
fullstate: 60s
peer:
abcd: 3322d
代码如下:
viper.SetConfigName(cmdRoot)
viper.AddConfigPath("./")
err := viper.ReadInConfig()
if err != nil {
fmt.Println(fmt.Errorf("Fatal error when reading %s config file: %s\n", cmdRoot, err))
}
environment := viper.GetBool("security.enabled")
fmt.Println("environment:", environment)
fullstate := viper.GetString("statetransfer.timeout.fullstate")
fmt.Println("fullstate:", fullstate)
abcValue := viper.GetString("peer.abcd")
fmt.Println("abcdValuea is :", abcValue)
上面介绍了以下viper的简单功能,下面写个稍微复杂的实例。
1、首先,定义个配置文件对应的结构体:
type Configstruct {
PostgreSQL struct {
DSNstring `mapstructure:"dsn"`
Automigrate bool
DB string
} `mapstructure:"postgresql"`
Redis struct {
URLstring `mapstructure:"url"`
Pool *redis.Pool
}
}
2、利用viper的SetDefault方法设置变量
viper.SetDefault("postgresql.dsn", "postgres://localhost/loraserver_as?sslmode=disable")
viper.SetDefault("postgresql.automigrate", true)
viper.SetDefault("redis.url", "redis://localhost:6379")
3、解析viper数据到上述结构体中
var config Config
viper.Unmarshal(&config)
这样,就可以将步骤2中设置的默认配置映射到Config结构体对应的变量中了。
具体流程,首先viper的SetDefault方法,用“.”作为分隔符key,然后将其存储到map[string]interface{}结构内。下面在做viper.Unmarshal(&config)时,根据Config结构体中定义的mapstructure的tag值进行解析(其中mapstructure是个第三方包)。
网友评论