viper.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package core
  2. import (
  3. "flag"
  4. "fmt"
  5. "github.com/flipped-aurora/gin-vue-admin/server/core/internal"
  6. "github.com/gin-gonic/gin"
  7. "os"
  8. "path/filepath"
  9. "github.com/fsnotify/fsnotify"
  10. "github.com/spf13/viper"
  11. "github.com/flipped-aurora/gin-vue-admin/server/global"
  12. )
  13. // Viper //
  14. // 优先级: 命令行 > 环境变量 > 默认值
  15. // Author [SliverHorn](https://github.com/SliverHorn)
  16. func Viper(path ...string) *viper.Viper {
  17. var config string
  18. if len(path) == 0 {
  19. flag.StringVar(&config, "c", "", "choose config file.")
  20. flag.Parse()
  21. if config == "" { // 判断命令行参数是否为空
  22. if configEnv := os.Getenv(internal.ConfigEnv); configEnv == "" { // 判断 internal.ConfigEnv 常量存储的环境变量是否为空
  23. switch gin.Mode() {
  24. case gin.DebugMode:
  25. config = internal.ConfigDefaultFile
  26. case gin.ReleaseMode:
  27. config = internal.ConfigReleaseFile
  28. case gin.TestMode:
  29. config = internal.ConfigTestFile
  30. }
  31. fmt.Printf("您正在使用gin模式的%s环境名称,config的路径为%s\n", gin.Mode(), config)
  32. } else { // internal.ConfigEnv 常量存储的环境变量不为空 将值赋值于config
  33. config = configEnv
  34. fmt.Printf("您正在使用%s环境变量,config的路径为%s\n", internal.ConfigEnv, config)
  35. }
  36. } else { // 命令行参数不为空 将值赋值于config
  37. fmt.Printf("您正在使用命令行的-c参数传递的值,config的路径为%s\n", config)
  38. }
  39. } else { // 函数传递的可变参数的第一个值赋值于config
  40. config = path[0]
  41. fmt.Printf("您正在使用func Viper()传递的值,config的路径为%s\n", config)
  42. }
  43. v := viper.New()
  44. v.SetConfigFile(config)
  45. v.SetConfigType("yaml")
  46. err := v.ReadInConfig()
  47. if err != nil {
  48. panic(fmt.Errorf("Fatal error config file: %s \n", err))
  49. }
  50. v.WatchConfig()
  51. v.OnConfigChange(func(e fsnotify.Event) {
  52. fmt.Println("config file changed:", e.Name)
  53. if err = v.Unmarshal(&global.GVA_CONFIG); err != nil {
  54. fmt.Println(err)
  55. }
  56. })
  57. if err = v.Unmarshal(&global.GVA_CONFIG); err != nil {
  58. panic(err)
  59. }
  60. // root 适配性 根据root位置去找到对应迁移位置,保证root路径有效
  61. global.GVA_CONFIG.AutoCode.Root, _ = filepath.Abs("..")
  62. return v
  63. }