config.go 2.0 KB

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