config.go 1.9 KB

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