最近发现go好多东西都是event,可以通过监听event的状态,动态获取参数,简单的代码
func main() {
var config Config
viper.SetConfigName("conf") // 设置配置文件名 (不带后缀)
viper.AddConfigPath(".") // 第一个搜索路径
viper.AddConfigPath("./demo/main") // 第二个搜索路径
viper.AddConfigPath("./main/conf") // 第三个搜索路径
err := viper.ReadInConfig() // 读取配置数据
if err != nil {
fmt.Printf("Fatal error config file: %s \n", err)
}
_ = viper.Unmarshal(&config)
go func() {
viper.WatchConfig()
viper.OnConfigChange(func(e fsnotify.Event) {
fmt.Println("Config file changed:", e.Name)
_ = viper.ReadInConfig() // 读取配置数据
_ = viper.Unmarshal(&config)
})
}()
for {
fmt.Println(config)
time.Sleep(time.Second)
}
}