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.

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