官网地址:
GitHub - spf13/viper: Go configuration with fangs
常用操作:
Viper会按照下面的优先级。每个项目的优先级都高于它下面的项目:
- 显示调用
Set
设置值 - 命令行参数(flag)
- 环境变量
- 配置文件
- key/value存储
- 默认值
配置文件 config.yaml
(当前目录下)
host: "0.0.0.0"
mysql:
host: "127.0.0.1"
port: 3306
cache:
cache1:
max-items: 100
item-size: 64
cache2:
max-items: 200
item-size: 80
配置
viper.SetDefault("redis.port", "localhost:6379")
// viper.SetConfigFile("./config.yaml") // 配置文件路径,此行和下面两行效果相同
viper.SetConfigName("config") // 配置文件名
viper.SetConfigType("yaml") // 配置文件类型
viper.AddConfigPath("./") // 配置文件路径
err := viper.ReadInConfig() // 查找并读取配置文件
if err != nil {
panic(fmt.Errorf("fatal error config file: %w", err)) // 处理错误
}
从Viper获取值
在Viper中,有几种方法可以根据值的类型获取值。存在以下功能和方法:
Get(key string) : interface{}
GetBool(key string) : bool
GetFloat64(key string) : float64
GetInt(key string) : int
GetIntSlice(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
AllSettings() : map[string]interface{}
通过传入.分隔的路径
// Viper可以通过传入.分隔的路径来访问嵌套字段:
mysqlHost := viper.GetString("mysql.host") // 访问mysql的host字段
fmt.Println("Mysql Host:", mysqlHost)
mysqlPort := viper.GetInt("mysql.port") // 访问mysql的port字段
fmt.Println("Mysql Port:", mysqlPort)
提取子树
// 提取子树
appConfig := viper.Sub("app") // 提取app子树
fmt.Println("App Config:", appConfig.AllSettings()) // 打印app子树的所有设置
cache1 := appConfig.GetStringMapString("cache1") // 提取app子树的cache1字段
cache2 := viper.Sub("app.cache2") // 提取app子树的cache2字段
fmt.Println("Cache1:", cache1) // 打印app子树的cache字段
fmt.Println("Cache2:", cache2.AllSettings()) // 打印app子树的cache2字段的所有设置
反序列化
// 反序列化
var conf Config
err = viper.Unmarshal(&conf) // 反序列化到结构体
if err != nil {
panic(fmt.Errorf("unable to decode into struct, %v", err)) // 处理错误
}
fmt.Println("Config Struct:", conf) // 打印反序列化后的结构体