config.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. }
  39. // Init 初始化配置
  40. func Init(rowVal *Config, path string) *viper.Viper {
  41. if path == "" {
  42. path = DefaultConfig
  43. }
  44. v := viper.GetViper()
  45. v.AutomaticEnv()
  46. v.SetEnvKeyReplacer(strings.NewReplacer(".", "_", "-", "_"))
  47. v.SetEnvPrefix("RUSTDESK_API")
  48. v.SetConfigFile(path)
  49. v.SetConfigType("yaml")
  50. err := v.ReadInConfig()
  51. if err != nil {
  52. panic(fmt.Errorf("Fatal error config file: %s \n", err))
  53. }
  54. v.WatchConfig()
  55. v.OnConfigChange(func(e fsnotify.Event) {
  56. //配置文件修改监听
  57. fmt.Println("config file changed:", e.Name)
  58. if err2 := v.Unmarshal(rowVal); err2 != nil {
  59. fmt.Println(err2)
  60. }
  61. rowVal.Rustdesk.LoadKeyFile()
  62. rowVal.Rustdesk.ParsePort()
  63. })
  64. if err := v.Unmarshal(rowVal); err != nil {
  65. fmt.Println(err)
  66. }
  67. rowVal.Rustdesk.LoadKeyFile()
  68. rowVal.Rustdesk.ParsePort()
  69. return v
  70. }
  71. // ReadEnv 读取环境变量
  72. func ReadEnv(rowVal interface{}) *viper.Viper {
  73. v := viper.New()
  74. v.AutomaticEnv()
  75. if err := v.Unmarshal(rowVal); err != nil {
  76. fmt.Println(err)
  77. }
  78. return v
  79. }