【Web】go管理配置神器 viper库
建议看
viper 库的作用
viper适用与go应用程序中处理多种格式的配置文件(如 YAML、JSON、TOML 等) 它支持:
-
设置默认值 从 JSON、TOML、YAML、HCL、envfile 和 Java 属性配置文件中读取 实时观看和重新读取配置文件(可选) 从环境变量读取 从远程配置系统(etcd 或 Consul)读取,并观察更改 从命令行标志读取 从缓冲区读取 设置显式值
Viper 可以被认为是满足所有应用程序配置需求的注册表。
使用
- 安装
go get github.com/spf13/viper
- 创建一个名为 config.yaml 的 YAML 格式的配置文件,例如:
database: host: localhost port: 5432 user: myuser password: mypassword
- 编写主函数
package main
import (
"fmt"
"github.com/spf13/viper"
)
func main() {
viper.SetConfigFile("config.yaml") // 设置配置文件名
viper.SetConfigType("yaml") // 设置配置文件类型
viper.AddConfigPath(".") // 设置配置文件路径
err := viper.ReadInConfig() // 读取配置文件
if err != nil {
panic(fmt.Errorf("读取配置文件失败: %s
", err))
}
dbHost := viper.GetString("database.host") // 读取数据库主机名
dbPort := viper.GetInt("database.port") // 读取数据库端口号
dbUser := viper.GetString("database.user") // 读取数据库用户名
dbPassword := viper.GetString("database.password") // 读取数据库密码
fmt.Printf("%v %v %v %v ", dbHost, dbPort, dbUser, dbPassword)
// 使用配置信息连接数据库...
}
- 总的结构如下
├─go.mod ├─config └─main.go
viper 还有一些重要的函数
- viper.SetDefault(key string, value interface{}):设置默认值。如果在读取配置文件时找不到键值对,则使用默认值。
viper.SetDefault("database.host", "localhost")
viper.SetDefault("database.port", 5432)
- viper.GetString(key string) string:获取字符串类型的配置参数的值。
dbHost := viper.GetString("database.host")
- viper.GetInt(key string) int:获取整数类型的配置参数的值。
dbPort := viper.GetInt("database.port")
- viper.GetBool(key string) bool:获取布尔类型的配置参数的值。
debugMode := viper.GetBool("debug")
- viper.GetDuration(key string) time.Duration:获取持续时间类型的配置参数的值。
timeout := viper.GetDuration("timeout")
- viper.GetStringSlice(key string) []string:获取字符串切片类型的配置参数的值。
allowedIPs := viper.GetStringSlice("security.allowed_ips")
- viper.Set(key string, value interface{}):设置配置参数的值。
viper.Set("database.host", "db.example.com")
- viper.WatchConfig():监视配置文件的更改并重新加载配置文件。
viper.WatchConfig()
- viper.ReadInConfig():读取并解析指定的配置文件。
err := viper.ReadInConfig()
if err != nil {
fmt.Printf("读取配置文件失败: %s
", err)
}
这些函数是 Viper 中最常用的一些函数,但还有许多其他有用的函数,如 viper.AllSettings()、viper.IsSet()、viper.Unmarshal() 等。使用 Viper,你可以轻松地读取和管理你的应用程序的配置信息,而无需手动解析和处理配置文件。
