Golang viper简单使用

浏览:1639次阅读
2 条评论

Viper

github viper

viper 是一个配置解决方案,拥有丰富的特性:

  • 支持 JSON/TOML/YAML/HCL/envfile/Java properties 等多种格式的配置文件;
  • 可以设置监听配置文件的修改,修改时自动加载新的配置;
  • 从环境变量、命令行选项和 io.Reader 中读取配置;
  • 从远程配置系统中读取和监听修改,如 etcd/Consul;
  • 代码逻辑中显示设置键值。

监听配置修改

viper.SetConfigFile("./conf/app.yaml")
err := viper.ReadInConfig() // Find and read the config file
if err != nil { // Handle errors reading the config file
    panic(fmt.Errorf("Fatal error config file: %w \n", err))
}
viper.WriteConfig() // writes current config to predefined path set by 'viper.AddConfigPath()' and 'viper.SetConfigName'

安全写入配置

viper.WriteConfig() // writes current config to predefined path set by 'viper.AddConfigPath()' and 'viper.SetConfigName'
viper.SafeWriteConfig()
viper.WriteConfigAs("/path/to/my/.config")
viper.SafeWriteConfigAs("/path/to/my/.config") // will error since it has already been written
viper.SafeWriteConfigAs("/path/to/my/.other_config")

找到并读取配置

err := viper.ReadInConfig() // Find and read the config file
if err != nil { // Handle errors reading the config file
    panic(fmt.Errorf("Fatal error config file: %w \n", err))
}

简单使用案例

当前目录结构

├─conf
├─app.yaml
└─internal
├─cmd
├─consts
├─handler
├─model
└─service

方式 1 直接设置文件路径

v := viper.New()
v.SetConfigFile("./conf/app.yaml")
err = v.ReadInConfig()
if err != nil {log.Fatal("read config failed: %v", err)
}
a := v.Get("trust_trackers")
fmt.Println(a)

方式 2 设置文件目录类型

v := viper.New()

v.AddConfigPath("./conf")
v.SetConfigName("app")
v.SetConfigType("yaml")
err = v.ReadInConfig()
if err != nil {log.Fatal("read config failed: %v", err)
}
a := v.Get("trust_trackers")
fmt.Println(a)

conf/app.yaml 配置文件

trust_trackers: "asf"
正文完
 0
包子
版权声明:本站原创文章,由 包子 2021-12-31发表,共计1525字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
评论(2 条评论)
海天s
2022-04-27 14:19:06 回复

博客挺漂亮,用的什么工具和主题啊?

 Macintosh  Chrome  中国北京北京市电信