viper.go 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package core
  2. import (
  3. "flag"
  4. "fmt"
  5. "github.com/gin-gonic/gin"
  6. "os"
  7. "path/filepath"
  8. "wails-app/internal/core/internal"
  9. "github.com/fsnotify/fsnotify"
  10. "github.com/spf13/viper"
  11. "wails-app/internal/global"
  12. _ "wails-app/internal/packfile"
  13. )
  14. // Viper //
  15. // 优先级: 命令行 > 环境变量 > 默认值
  16. // Author [SliverHorn](https://github.com/SliverHorn)
  17. func Viper(path ...string) *viper.Viper {
  18. var config string
  19. if len(path) == 0 {
  20. flag.StringVar(&config, "c", "", "choose config file.")
  21. flag.Parse()
  22. if config == "" { // 判断命令行参数是否为空
  23. if configEnv := os.Getenv(internal.ConfigEnv); configEnv == "" { // 判断 internal.ConfigEnv 常量存储的环境变量是否为空
  24. switch gin.Mode() {
  25. case gin.DebugMode:
  26. config = internal.ConfigDefaultFile
  27. fmt.Printf("您正在使用gin模式的%s环境名称,config的路径为%s\n", gin.Mode(), internal.ConfigDefaultFile)
  28. case gin.ReleaseMode:
  29. config = internal.ConfigReleaseFile
  30. fmt.Printf("您正在使用gin模式的%s环境名称,config的路径为%s\n", gin.Mode(), internal.ConfigReleaseFile)
  31. case gin.TestMode:
  32. config = internal.ConfigTestFile
  33. fmt.Printf("您正在使用gin模式的%s环境名称,config的路径为%s\n", gin.Mode(), internal.ConfigTestFile)
  34. }
  35. } else { // internal.ConfigEnv 常量存储的环境变量不为空 将值赋值于config
  36. config = configEnv
  37. fmt.Printf("您正在使用%s环境变量,config的路径为%s\n", internal.ConfigEnv, config)
  38. }
  39. } else { // 命令行参数不为空 将值赋值于config
  40. fmt.Printf("您正在使用命令行的-c参数传递的值,config的路径为%s\n", config)
  41. }
  42. } else { // 函数传递的可变参数的第一个值赋值于config
  43. config = path[0]
  44. fmt.Printf("您正在使用func Viper()传递的值,config的路径为%s\n", config)
  45. }
  46. v := viper.New()
  47. v.SetConfigFile(config)
  48. v.SetConfigType("yaml")
  49. err := v.ReadInConfig()
  50. // If config.yaml not found in CWD, try next to the executable
  51. if err != nil {
  52. if exePath, exeErr := os.Executable(); exeErr == nil {
  53. exeDir := filepath.Dir(exePath)
  54. fallbackConfig := filepath.Join(exeDir, config)
  55. if _, statErr := os.Stat(fallbackConfig); statErr == nil {
  56. fmt.Printf("使用可执行文件目录的config: %s\n", fallbackConfig)
  57. v.SetConfigFile(fallbackConfig)
  58. err = v.ReadInConfig()
  59. }
  60. }
  61. }
  62. if err != nil {
  63. panic(fmt.Errorf("Fatal error config file: %s \n", err))
  64. }
  65. v.WatchConfig()
  66. v.OnConfigChange(func(e fsnotify.Event) {
  67. fmt.Println("config file changed:", e.Name)
  68. if err = v.Unmarshal(&global.GVA_CONFIG); err != nil {
  69. fmt.Println(err)
  70. }
  71. })
  72. if err = v.Unmarshal(&global.GVA_CONFIG); err != nil {
  73. panic(err)
  74. }
  75. return v
  76. }