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.

57 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. v.SetConfigType("yaml")
  36. err := v.ReadInConfig()
  37. if err != nil {
  38. panic(fmt.Errorf("Fatal error config file: %s \n", err))
  39. }
  40. v.WatchConfig()
  41. v.OnConfigChange(func(e fsnotify.Event) {
  42. fmt.Println("config file changed:", e.Name)
  43. if err := v.Unmarshal(&global.GVA_CONFIG); err != nil {
  44. fmt.Println(err)
  45. }
  46. })
  47. if err := v.Unmarshal(&global.GVA_CONFIG); err != nil {
  48. fmt.Println(err)
  49. }
  50. global.GVA_CONFIG.AutoCode.Root, _ = filepath.Abs("..")
  51. return v
  52. }