> 文章列表 > [Golang]每日一库-viper

[Golang]每日一库-viper

[Golang]每日一库-viper

😚一个不甘平凡的普通人,致力于为Golang社区和算法学习做出贡献,期待您的关注和认可,陪您一起学习打卡!!!😘😘😘
🤗专栏:算法学习
🤗专栏:Go实战
💬个人主页:个人主页

文章目录

  • viper是什么?
  • 快速上手

viper是什么?

解决程序相关配置,支持多种文件格式,方便快捷,简化配置过程,易修改配置参数

  1. 默认配置
  2. 从 JSON, TOML, YAML, HCL 和 Java 属性配置文件读取数据
  3. 实时查看和重新读取配置文件(可选)
  4. 从环境变量中读取
  5. 从远程配置系统(etcd 或 Consul)读取数据并监听变化
  6. 从命令行参数读取
  7. 从 buffer 中读取
  8. 设置显式值

快速上手

终端引入viper依赖

go get github.com/spf13/viper

常用方法:

viper.SetConfigFile("haha")      //配置文件名,不需要后缀viper.SetConfigType("yaml")      //设置配置文件格式viper.AddConfigPath("../config") //查找路径err := viper.ReadInConfig()      //读取配置文件if err != nil {panic(fmt.Errorf("fail to find config,please revise it (viper/config)"))}//监听配置文件,当配置文件改变的时候,不需要重新启动viper.OnConfigChange(func(e fsnotify.Event) {fmt.Println("Config file changed:", e.Name)})

对应go中的mysql写法

mysql:host: 127.0.0.1port: 3306username: xxxxpassword: xxxxmethod: tcpdatabase: xxxxconfig: charset=utf8mb4&parseTime=True&loc=Local

注意点:
接收的结构体内部需要跟yaml的字段进行绑定;
默认情况下,mapstructure使用结构体中字段的名称做这个映射

type Mysql struct {Host     string `mapstructure:"host"`Port     string `mapstructure:"port"`Username string `mapstructure:"username"`Password string `mapstructure:"password"`Method   string `mapstructure:"method"`Database string `mapstructure:"database"`Config   string `mapstructure:"config"`
}

官方文档:
https://geekdaxue.co/read/go-packages-docs-awesome/docs-viper-README.md