viper.go 2.1 KB

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