config.go 1.8 KB

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