You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

48 lines
1.2 KiB

  1. package core
  2. import (
  3. "flag"
  4. "fmt"
  5. "gin-vue-admin/global"
  6. _ "gin-vue-admin/packfile"
  7. "gin-vue-admin/utils"
  8. "github.com/fsnotify/fsnotify"
  9. "github.com/spf13/viper"
  10. "os"
  11. )
  12. var config string
  13. func init() {
  14. flag.StringVar(&config, "c", "", "choose config file.")
  15. flag.Parse()
  16. if config == "" { // 优先级: 命令行 > 环境变量 > 默认值
  17. if configEnv := os.Getenv(utils.ConfigEnv); configEnv == "" {
  18. config = utils.ConfigFile
  19. fmt.Printf("您正在使用config的默认值,config的路径为%v\n", utils.ConfigFile)
  20. } else {
  21. config = configEnv
  22. fmt.Printf("您正在使用GVA_CONFIG环境变量,config的路径为%v\n", config)
  23. }
  24. } else {
  25. fmt.Printf("您正在使用命令行的-c参数传递的值,config的路径为%v\n", config)
  26. }
  27. v := viper.New()
  28. v.SetConfigFile(config)
  29. err := v.ReadInConfig()
  30. if err != nil {
  31. panic(fmt.Errorf("Fatal error config file: %s \n", err))
  32. }
  33. v.WatchConfig()
  34. v.OnConfigChange(func(e fsnotify.Event) {
  35. fmt.Println("config file changed:", e.Name)
  36. if err := v.Unmarshal(&global.GVA_CONFIG); err != nil {
  37. fmt.Println(err)
  38. }
  39. })
  40. if err := v.Unmarshal(&global.GVA_CONFIG); err != nil {
  41. fmt.Println(err)
  42. }
  43. global.GVA_VP = v
  44. }