config.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package config
  2. import (
  3. "fmt"
  4. "github.com/fsnotify/fsnotify"
  5. "github.com/spf13/viper"
  6. "strings"
  7. )
  8. const (
  9. DebugMode = "debug"
  10. ReleaseMode = "release"
  11. DefaultConfig = "conf/config.yaml"
  12. )
  13. type App struct {
  14. WebClient int `mapstructure:"web-client"`
  15. Register bool `mapstructure:"register"`
  16. }
  17. type Config struct {
  18. Lang string `mapstructure:"lang"`
  19. App App
  20. Gorm Gorm
  21. Mysql Mysql
  22. Gin Gin
  23. Logger Logger
  24. Redis Redis
  25. Cache Cache
  26. Oss Oss
  27. Jwt Jwt
  28. Rustdesk Rustdesk
  29. Proxy Proxy
  30. }
  31. // Init 初始化配置
  32. func Init(rowVal interface{}, path string) *viper.Viper {
  33. if path == "" {
  34. path = DefaultConfig
  35. }
  36. v := viper.GetViper()
  37. v.AutomaticEnv()
  38. v.SetEnvKeyReplacer(strings.NewReplacer(".", "_", "-", "_"))
  39. v.SetEnvPrefix("RUSTDESK_API")
  40. v.SetConfigFile(path)
  41. v.SetConfigType("yaml")
  42. err := v.ReadInConfig()
  43. if err != nil {
  44. panic(fmt.Errorf("Fatal error config file: %s \n", err))
  45. }
  46. v.WatchConfig()
  47. v.OnConfigChange(func(e fsnotify.Event) {
  48. //配置文件修改监听
  49. fmt.Println("config file changed:", e.Name)
  50. if err2 := v.Unmarshal(rowVal); err2 != nil {
  51. fmt.Println(err2)
  52. }
  53. })
  54. if err := v.Unmarshal(rowVal); err != nil {
  55. fmt.Println(err)
  56. }
  57. return v
  58. }
  59. // ReadEnv 读取环境变量
  60. func ReadEnv(rowVal interface{}) *viper.Viper {
  61. v := viper.New()
  62. v.AutomaticEnv()
  63. if err := v.Unmarshal(rowVal); err != nil {
  64. fmt.Println(err)
  65. }
  66. return v
  67. }