package core import ( "flag" "fmt" "mtp20_assisted/global" "github.com/fsnotify/fsnotify" "github.com/spf13/viper" ) // 优先级: 命令行 > 环境变量 > 默认值 func Viper(path ...string) *viper.Viper { var config string if len(path) == 0 { flag.StringVar(&config, "c", "", "choose config file.") flag.Parse() config = "config.yaml" } else { // 函数传递的可变参数的第一个值赋值于config config = path[0] fmt.Printf("您正在使用func Viper()传递的值,config的路径为%s\n", config) } v := viper.New() v.SetConfigFile(config) v.SetConfigType("yaml") err := v.ReadInConfig() if err != nil { panic(fmt.Errorf("fatal error config file: %s", err)) } v.WatchConfig() v.OnConfigChange(func(e fsnotify.Event) { fmt.Println("config file changed:", e.Name) if err = v.Unmarshal(&global.M2A_CONFIG); err != nil { fmt.Println(err) } }) if err = v.Unmarshal(&global.M2A_CONFIG); err != nil { fmt.Println(err) } return v }