viper.go 990 B

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