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.

69 lines
1.9 KiB

3 years ago
3 years ago
3 years ago
  1. package core
  2. import (
  3. "flag"
  4. "fmt"
  5. "os"
  6. "path/filepath"
  7. "time"
  8. "github.com/flipped-aurora/gin-vue-admin/server/service/system"
  9. "github.com/songzhibin97/gkit/cache/local_cache"
  10. "github.com/flipped-aurora/gin-vue-admin/server/global"
  11. _ "github.com/flipped-aurora/gin-vue-admin/server/packfile"
  12. "github.com/flipped-aurora/gin-vue-admin/server/utils"
  13. "github.com/fsnotify/fsnotify"
  14. "github.com/spf13/viper"
  15. )
  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(utils.ConfigEnv); configEnv == "" {
  23. config = utils.ConfigFile
  24. fmt.Printf("您正在使用config的默认值,config的路径为%v\n", utils.ConfigFile)
  25. } else {
  26. config = configEnv
  27. fmt.Printf("您正在使用GVA_CONFIG环境变量,config的路径为%v\n", config)
  28. }
  29. } else {
  30. fmt.Printf("您正在使用命令行的-c参数传递的值,config的路径为%v\n", config)
  31. }
  32. } else {
  33. config = path[0]
  34. fmt.Printf("您正在使用func Viper()传递的值,config的路径为%v\n", config)
  35. }
  36. v := viper.New()
  37. v.SetConfigFile(config)
  38. v.SetConfigType("yaml")
  39. err := v.ReadInConfig()
  40. if err != nil {
  41. panic(fmt.Errorf("Fatal error config file: %s \n", err))
  42. }
  43. v.WatchConfig()
  44. v.OnConfigChange(func(e fsnotify.Event) {
  45. fmt.Println("config file changed:", e.Name)
  46. if err := v.Unmarshal(&global.GVA_CONFIG); err != nil {
  47. fmt.Println(err)
  48. }
  49. })
  50. if err := v.Unmarshal(&global.GVA_CONFIG); err != nil {
  51. fmt.Println(err)
  52. }
  53. global.GVA_CONFIG.AutoCode.Root, _ = filepath.Abs("..")
  54. global.BlackCache = local_cache.NewCache(
  55. local_cache.SetDefaultExpire(time.Duration(global.GVA_CONFIG.JWT.ExpiresTime)))
  56. // 从db加载jwt数据
  57. if global.GVA_DB != nil {
  58. system.LoadAll()
  59. }
  60. return v
  61. }