viper.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. package core
  2. import (
  3. "flag"
  4. "fmt"
  5. "os"
  6. "path/filepath"
  7. "github.com/flipped-aurora/gin-vue-admin/server/global"
  8. _ "github.com/flipped-aurora/gin-vue-admin/server/packfile"
  9. "github.com/flipped-aurora/gin-vue-admin/server/utils"
  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. }