这是我参与「第五届青训营 」伴学笔记创作活动的第 15 天
Day15
Viper
go get github.com/spf13/viper
What
Viper是Go应用程序的完整配置解决方案,包括12-Factor应用程序。
它在应用程序中工作,并可以处理所有类型的配置需求和格式。
它支持:
- 设置默认值
- 从JSON,TOML,YAML,HCL和Java属性配置文件中读取
- 实时观看和重新读取配置文件(可选)
- 从环境变量中读取
- 从远程配置系统(etcd或Consul)读取,并观察变化
- 从命令行标志读取
- 从缓冲区读取
- 设置显式值
Viper可以被认为是你的所有应用程序配置需求的注册表。
Why
构建现代应用程序时,您不想操心配置文件格式,你想专注于构建很棒的软件。Viper就是为此提供帮助的。
Viper为您做了以下事情:
- 以JSON,TOML,YAML,HCL或Java Properties格式查找,加载和解组配置文件。
- 支持为不同的配置选项设置默认值。
- 支持通过命令行标志覆盖对应配置选项。
- 提供别名系统,轻松重命名参数,而不会破坏现有代码。
- Make it easy to tell the difference between when a user has provided a command line or config file which is the same as the default.
Viper使用以下优先顺序。每个项目优先于其下方的项目:
- explicit call to
Set - flag
- env
- config
- key/value store
- default
Important: Viper configuration keys are case insensitive(大小写不敏感,不区分大小写).
There are ongoing discussions about making that optional.
使用Viper设置默认值
viper.SetDefault("ContentDir", "content")
viper.SetDefault("Taxonomies", map[string]string{"tag": "tags", "category": "categories"})
Viper读取配置文件
Viper可以搜索多个路径,但目前一个Viper实例只支持一个配置文件。Viper不默认任何配置搜索路径,而是将默认决定权留给一个应用程序。
下面是一个如何使用Viper来搜索和读取配置文件的例子。这些特定的路径都不是必须的,但应该提供至少一个期望有配置文件的路径。
viper.SetConfigName("config") // name of config file (without extension)
viper.SetConfigType("yaml") // REQUIRED if the config file does not have the extension in the name
viper.AddConfigPath("/etc/appname/") // path to look for the config file in
viper.AddConfigPath("$HOME/.appname") // call multiple times to add many search paths
viper.AddConfigPath(".") // optionally look for config in the working directory
err := viper.ReadInConfig() // Find and read the config file
if err != nil { // Handle errors reading the config file
if _, ok := err.(viper.ConfigFileNotFoundError); ok {
// Config file not found; ignore error if desired
} else {
// Config file was found but another error was produced
}
}
// Config file found and successfully parsed
从Viper中获取值
在Viper中,有几种方法可以获得一个值,这取决于该值的类型。
需要注意的是,如果没有找到,Get函数将返回一个0值。
IsSet()方法可以检查一个给定的键是否存在。
viper.GetString("logfile") // case-insensitive Setting & Getting
if viper.GetBool("verbose") {
fmt.Println("verbose enabled")
}