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.

56 lines
1.4 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. "os"
  9. "path/filepath"
  10. "github.com/fsnotify/fsnotify"
  11. "github.com/spf13/viper"
  12. )
  13. func Viper(path ...string) *viper.Viper {
  14. var config string
  15. if len(path) == 0 {
  16. flag.StringVar(&config, "c", "", "choose config file.")
  17. flag.Parse()
  18. if config == "" { // 优先级: 命令行 > 环境变量 > 默认值
  19. if configEnv := os.Getenv(utils.ConfigEnv); configEnv == "" {
  20. config = utils.ConfigFile
  21. fmt.Printf("您正在使用config的默认值,config的路径为%v\n", utils.ConfigFile)
  22. } else {
  23. config = configEnv
  24. fmt.Printf("您正在使用GVA_CONFIG环境变量,config的路径为%v\n", config)
  25. }
  26. } else {
  27. fmt.Printf("您正在使用命令行的-c参数传递的值,config的路径为%v\n", config)
  28. }
  29. } else {
  30. config = path[0]
  31. fmt.Printf("您正在使用func Viper()传递的值,config的路径为%v\n", config)
  32. }
  33. v := viper.New()
  34. v.SetConfigFile(config)
  35. err := v.ReadInConfig()
  36. if err != nil {
  37. panic(fmt.Errorf("Fatal error config file: %s \n", err))
  38. }
  39. v.WatchConfig()
  40. v.OnConfigChange(func(e fsnotify.Event) {
  41. fmt.Println("config file changed:", e.Name)
  42. if err := v.Unmarshal(&global.GVA_CONFIG); err != nil {
  43. fmt.Println(err)
  44. }
  45. })
  46. if err := v.Unmarshal(&global.GVA_CONFIG); err != nil {
  47. fmt.Println(err)
  48. }
  49. global.GVA_CONFIG.AutoCode.Root, _ = filepath.Abs("..")
  50. return v
  51. }