config.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package core
  2. import (
  3. "fmt"
  4. "github.com/fsnotify/fsnotify"
  5. "github.com/spf13/viper"
  6. "hongze/hongze_yb/global"
  7. "hongze/hongze_yb/utils"
  8. )
  9. const ConfigFile = "config/config.yaml" //本地(测试)环境下的配置文件地址
  10. const ProConfigFile = "/home/code/config/hongze_yb/config/config.yaml" //生产环境下的配置文件地址
  11. func init() {
  12. v := viper.New()
  13. configFilePath := ConfigFile
  14. //如果不存在该配置文件,那么应该是线上环境,那么去寻找线上配置文件的路径
  15. if !utils.FileIsExist(configFilePath) {
  16. configFilePath = ProConfigFile
  17. }
  18. //设置配置文件
  19. v.SetConfigFile(configFilePath)
  20. err := v.ReadInConfig()
  21. if err != nil {
  22. panic(fmt.Errorf("读取配置失败,Err: %s \n", err))
  23. }
  24. //持续监听文件
  25. v.WatchConfig()
  26. v.OnConfigChange(func(e fsnotify.Event) {
  27. fmt.Println("配置文件变更:", e.Name)
  28. if err := v.Unmarshal(&global.CONFIG); err != nil {
  29. fmt.Println("配置重赋值失败,Err:", err)
  30. }
  31. fmt.Println(global.CONFIG)
  32. })
  33. if err := v.Unmarshal(&global.CONFIG); err != nil {
  34. fmt.Println("配置初始化赋值失败,Err:", err)
  35. }
  36. }