config.go 2.2 KB

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