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.

64 lines
1.7 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/songzhibin97/gkit/cache/local_cache"
  9. "github.com/flipped-aurora/gin-vue-admin/server/global"
  10. _ "github.com/flipped-aurora/gin-vue-admin/server/packfile"
  11. "github.com/flipped-aurora/gin-vue-admin/server/utils"
  12. "github.com/fsnotify/fsnotify"
  13. "github.com/spf13/viper"
  14. )
  15. func Viper(path ...string) *viper.Viper {
  16. var config string
  17. if len(path) == 0 {
  18. flag.StringVar(&config, "c", "", "choose config file.")
  19. flag.Parse()
  20. if config == "" { // 优先级: 命令行 > 环境变量 > 默认值
  21. if configEnv := os.Getenv(utils.ConfigEnv); configEnv == "" {
  22. config = utils.ConfigFile
  23. fmt.Printf("您正在使用config的默认值,config的路径为%v\n", utils.ConfigFile)
  24. } else {
  25. config = configEnv
  26. fmt.Printf("您正在使用GVA_CONFIG环境变量,config的路径为%v\n", config)
  27. }
  28. } else {
  29. fmt.Printf("您正在使用命令行的-c参数传递的值,config的路径为%v\n", config)
  30. }
  31. } else {
  32. config = path[0]
  33. fmt.Printf("您正在使用func Viper()传递的值,config的路径为%v\n", config)
  34. }
  35. v := viper.New()
  36. v.SetConfigFile(config)
  37. v.SetConfigType("yaml")
  38. err := v.ReadInConfig()
  39. if err != nil {
  40. panic(fmt.Errorf("Fatal error config file: %s \n", err))
  41. }
  42. v.WatchConfig()
  43. v.OnConfigChange(func(e fsnotify.Event) {
  44. fmt.Println("config file changed:", e.Name)
  45. if err := v.Unmarshal(&global.GVA_CONFIG); err != nil {
  46. fmt.Println(err)
  47. }
  48. })
  49. if err := v.Unmarshal(&global.GVA_CONFIG); err != nil {
  50. fmt.Println(err)
  51. }
  52. global.GVA_CONFIG.AutoCode.Root, _ = filepath.Abs("..")
  53. global.BlackCache = local_cache.NewCache(
  54. local_cache.SetDefaultExpire(time.Second * time.Duration(global.GVA_CONFIG.JWT.ExpiresTime))
  55. )
  56. return v
  57. }