golang viper配置文件管理包使用

1.安装

go get github.com/spf13/viper

2.基本使用及注意事项
config.toml文件,注意事项在程序注释中
appname = "user_web77"loglevel = "info" port = 8089[mysql] ip = "192.168.56.19" port = 3310 user = "root" password = 123456 database = "cmp"[redis] ip = "192.168.56.101" port = 6379[rabbitmq] ip = "192.168.56.101" port = 5991

【golang viper配置文件管理包使用】程序
package mainimport ( "fmt" "github.com/fsnotify/fsnotify" "github.com/spf13/viper" "log" "time" )type MysqlConfig struct{ Ip string//公有访问 Port string User string Password string Database string }type RedisConfig struct{ Ip string Port string }type RabbitmqConfig struct{ Ip string Port string }type Config struct{//Config对象和config.toml文件保持一致 AppName string LogLevel string Port string Mysql MysqlConfig//需要定义子类型对应的变量,如果不定义映射不成功 Redis RedisConfig Rabbitmq RabbitmqConfig }func main() { viper.AutomaticEnv()//获取环境变量的值 viper.SetConfigName("config")//定义配置文件名称 viper.SetConfigType("toml")//定义格式 viper.AddConfigPath("./config/")//定义文件路径 viper.SetDefault("redis.port",6379)//设置默认值 viper.SetDefault("kafka.port",6856) err := viper.ReadInConfig()//读取 if err != nil { log.Fatalln("read config failed: %v",err) } viper.WatchConfig()//监听配置文件改变并且需要放置在viper.ReadInConfig之后 viper.OnConfigChange(func(e fsnotify.Event) { //配置文件修改完后的回调函数 log.Printf("Config file:%s Op:%s\n", e.Name, e.Op) }) log.Println(viper.GetString("appname"))//以string格式获取 log.Println(viper.GetString("log_level")) log.Println(viper.GetString("port"))fmt.Println("mysql ip:",viper.GetString("mysql.ip")) fmt.Println("mysql port:",viper.GetString("mysql.port")) fmt.Println("kafka port:",viper.GetString("kafka.port")) fmt.Println("GOPATH: ", viper.Get("GOPATH")) time.Sleep(time.Second)var config Config viper.Unmarshal(&config)for { log.Println(config.LogLevel)//通过绑定到对象上不会实时更新 log.Println(config.AppName) log.Println(config.Mysql.Ip) fmt.Println("mysql ip:",viper.GetString("mysql.ip"))//可以更新 time.Sleep(time.Second * 5) }}

3.结果
2021/08/03 14:31:25 info 2021/08/03 14:31:25 user_web77 2021/08/03 14:31:25 192.168.56.138 mysql ip: 192.168.56.138 2021/08/03 14:31:28 Config file:C:\Users\admin\xiayuedu\golangdemo\config\config.toml Op:WRITE 2021/08/03 14:31:28 Config file:C:\Users\admin\xiayuedu\golangdemo\config\config.toml Op:WRITE 2021/08/03 14:31:30 info 2021/08/03 14:31:30 user_web77 2021/08/03 14:31:30 192.168.56.138 mysql ip: 192.168.56.19 2021/08/03 14:31:35 info 2021/08/03 14:31:35 user_web77 2021/08/03 14:31:35 192.168.56.138 mysql ip: 192.168.56.19

    推荐阅读