config.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package config
  2. import (
  3. "flag"
  4. "fmt"
  5. "github.com/fsnotify/fsnotify"
  6. "github.com/spf13/viper"
  7. )
  8. const (
  9. DebugMode = "debug"
  10. ReleaseMode = "release"
  11. DefaultConfig = "conf/config.yaml"
  12. )
  13. type Config struct {
  14. Gorm Gorm
  15. Mysql Mysql
  16. Gin Gin
  17. Logger Logger
  18. Redis Redis
  19. Cache Cache
  20. Oss Oss
  21. Jwt Jwt
  22. Rustdesk Rustdesk
  23. }
  24. // Init 初始化配置
  25. func Init(rowVal interface{}, cb func()) *viper.Viper {
  26. var config string
  27. flag.StringVar(&config, "c", "", "choose config file.")
  28. flag.Parse()
  29. if config == "" { // 优先级: 命令行 > 默认值
  30. config = DefaultConfig
  31. }
  32. v := viper.New()
  33. v.SetConfigFile(config)
  34. v.SetConfigType("yaml")
  35. err := v.ReadInConfig()
  36. if err != nil {
  37. panic(fmt.Errorf("Fatal error config file: %s \n", err))
  38. }
  39. v.WatchConfig()
  40. v.OnConfigChange(func(e fsnotify.Event) {
  41. //配置文件修改监听
  42. fmt.Println("config file changed:", e.Name)
  43. if err2 := v.Unmarshal(rowVal); err2 != nil {
  44. fmt.Println(err2)
  45. }
  46. cb()
  47. })
  48. if err := v.Unmarshal(rowVal); err != nil {
  49. fmt.Println(err)
  50. }
  51. return v
  52. }