viper.go 1002 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. package core
  2. import (
  3. "fmt"
  4. "mtp20_assisted/global"
  5. "github.com/fsnotify/fsnotify"
  6. "github.com/spf13/viper"
  7. )
  8. // 优先级: 命令行 > 环境变量 > 默认值
  9. func Viper(path ...string) *viper.Viper {
  10. var config string
  11. // if len(path) == 0 {
  12. // flag.StringVar(&config, "c", "", "choose config file.")
  13. // flag.Parse()
  14. config = "config.yaml"
  15. // } else { // 函数传递的可变参数的第一个值赋值于config
  16. // config = path[0]
  17. // fmt.Printf("您正在使用func Viper()传递的值,config的路径为%s\n", config)
  18. // }
  19. v := viper.New()
  20. v.SetConfigFile(config)
  21. v.SetConfigType("yaml")
  22. err := v.ReadInConfig()
  23. if err != nil {
  24. panic(fmt.Errorf("fatal error config file: %s", err))
  25. }
  26. v.WatchConfig()
  27. v.OnConfigChange(func(e fsnotify.Event) {
  28. fmt.Println("config file changed:", e.Name)
  29. if err = v.Unmarshal(&global.M2A_CONFIG); err != nil {
  30. fmt.Println(err)
  31. }
  32. })
  33. if err = v.Unmarshal(&global.M2A_CONFIG); err != nil {
  34. fmt.Println(err)
  35. }
  36. return v
  37. }