viper
主要是用于处理各种格式的配置文件,简化程序配置的读取问题支持
- 设置默认配置
- 支持读取 JSON TOML YAML HCL 和 Java 属性配置文件
- 监听配置文件变化,实时读取读取配置文件内容
- 读取环境变量值
- 读取远程配置系统 (etcd Consul) 和监控配置变化
- 读取命令 Flag 值
- 读取 buffer 值
- 读取确切值
viper 项目地址 github.com/spf13/viper
使用方式
安装
go get github.com/spf13/viper
根据路径读取配置文件
目前使用yaml比较多,这里以yaml为例
proxyconfig:
- localport: 43306
remoteip: 192.168.1.100
remoteport: 3306
enable: false
network: tcp
创建对应的结构体
type Config struct {
ProxyConfig []ProxyConfig
}
type ProxyConfig struct {
LocalPort int
RemoteIp string
RemotePort int
Enable bool
Network string
}
读取配置文件
v := viper.New()
v.SetConfigFile("./demo.yaml")
v.SetConfigType("yaml")
if err := v.ReadInConfig(); err != nil {
panic(err)
}
config := Config{}
if err := v.Unmarshal(&config); err != nil {
panic(err)
}
fmt.Println(config)
写出配置文件到指定路径
v := viper.New()
v.SetConfigFile("./demo.yaml")
v.SetConfigType("yaml")
v.Set("ProxyConfig", []handler.ProxyConfig{{
LocalPort: 43306,
RemoteIp: "192.168.1.100",
RemotePort: 3306,
Network: "tcp",
}})
if err := v.WriteConfig(); err != nil {
panic(err)
}
- viper.WriteConfig() //写出文件 覆盖
- viper.SafeWriteConfig() // 安全写出 不覆盖,抛出异常
- viper.WriteConfigAs(“/path/to/my/.config”) //写出到指定路径 覆盖
- viper.SafeWriteConfigAs(“/path/to/my/.config”) //安全写出到指定路径 不覆盖