Golang viper简单使用

Viper

[github author="spf13" project="viper"][/github]
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"

给TA打赏
共{{data.count}}人
人已打赏
杂七杂八

kodexplorer 中 第三方插件 OnlyOffice 分享文档报错解决

2021-10-27 11:11:20

杂七杂八

qBittorrent 下载器 全自动限制非信任PT Tracker分享率 分享时间

2022-1-6 10:42:32

2 条回复A文章作者M管理员
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索