config.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. package config
  2. import (
  3. "fmt"
  4. "github.com/spf13/viper"
  5. "strings"
  6. "time"
  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. RegisterStatus int `mapstructure:"register-status"`
  17. ShowSwagger int `mapstructure:"show-swagger"`
  18. TokenExpire time.Duration `mapstructure:"token-expire"`
  19. WebSso bool `mapstructure:"web-sso"`
  20. DisablePwdLogin bool `mapstructure:"disable-pwd-login"`
  21. CaptchaThreshold int `mapstructure:"captcha-threshold"`
  22. BanThreshold int `mapstructure:"ban-threshold"`
  23. }
  24. type Admin struct {
  25. Title string `mapstructure:"title"`
  26. Hello string `mapstructure:"hello"`
  27. HelloFile string `mapstructure:"hello-file"`
  28. }
  29. type Config struct {
  30. Lang string `mapstructure:"lang"`
  31. App App
  32. Admin Admin
  33. Gorm Gorm
  34. Mysql Mysql
  35. Gin Gin
  36. Logger Logger
  37. Redis Redis
  38. Cache Cache
  39. Oss Oss
  40. Jwt Jwt
  41. Rustdesk Rustdesk
  42. Proxy Proxy
  43. Ldap Ldap
  44. }
  45. // Init 初始化配置
  46. func Init(rowVal *Config, path string) *viper.Viper {
  47. if path == "" {
  48. path = DefaultConfig
  49. }
  50. v := viper.GetViper()
  51. v.AutomaticEnv()
  52. v.SetEnvKeyReplacer(strings.NewReplacer(".", "_", "-", "_"))
  53. v.SetEnvPrefix("RUSTDESK_API")
  54. v.SetConfigFile(path)
  55. v.SetConfigType("yaml")
  56. err := v.ReadInConfig()
  57. if err != nil {
  58. panic(fmt.Errorf("Fatal error config file: %s \n", err))
  59. }
  60. /*
  61. v.WatchConfig()
  62. //监听配置修改没什么必要
  63. v.OnConfigChange(func(e fsnotify.Event) {
  64. //配置文件修改监听
  65. fmt.Println("config file changed:", e.Name)
  66. if err2 := v.Unmarshal(rowVal); err2 != nil {
  67. fmt.Println(err2)
  68. }
  69. rowVal.Rustdesk.LoadKeyFile()
  70. rowVal.Rustdesk.ParsePort()
  71. })
  72. */
  73. if err := v.Unmarshal(rowVal); err != nil {
  74. panic(fmt.Errorf("Fatal error config: %s \n", err))
  75. }
  76. rowVal.Rustdesk.LoadKeyFile()
  77. rowVal.Rustdesk.ParsePort()
  78. return v
  79. }
  80. // ReadEnv 读取环境变量
  81. func ReadEnv(rowVal interface{}) *viper.Viper {
  82. v := viper.New()
  83. v.AutomaticEnv()
  84. if err := v.Unmarshal(rowVal); err != nil {
  85. fmt.Println(err)
  86. }
  87. return v
  88. }