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
程序
package main
import (
"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