config.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. }
  18. type Admin struct {
  19. Title string `mapstructure:"title"`
  20. Hello string `mapstructure:"hello"`
  21. HelloFile string `mapstructure:"hello-file"`
  22. }
  23. type Config struct {
  24. Lang string `mapstructure:"lang"`
  25. App App
  26. Admin Admin
  27. Gorm Gorm
  28. Mysql Mysql
  29. Gin Gin
  30. Logger Logger
  31. Redis Redis
  32. Cache Cache
  33. Oss Oss
  34. Jwt Jwt
  35. Rustdesk Rustdesk
  36. Proxy Proxy
  37. Ldap Ldap
  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. /*
  56. //监听配置修改没什么必要
  57. v.OnConfigChange(func(e fsnotify.Event) {
  58. //配置文件修改监听
  59. fmt.Println("config file changed:", e.Name)
  60. if err2 := v.Unmarshal(rowVal); err2 != nil {
  61. fmt.Println(err2)
  62. }
  63. rowVal.Rustdesk.LoadKeyFile()
  64. rowVal.Rustdesk.ParsePort()
  65. })
  66. */
  67. if err := v.Unmarshal(rowVal); err != nil {
  68. fmt.Println(err)
  69. }
  70. rowVal.Rustdesk.LoadKeyFile()
  71. rowVal.Rustdesk.ParsePort()
  72. return v
  73. }
  74. // ReadEnv 读取环境变量
  75. func ReadEnv(rowVal interface{}) *viper.Viper {
  76. v := viper.New()
  77. v.AutomaticEnv()
  78. if err := v.Unmarshal(rowVal); err != nil {
  79. fmt.Println(err)
  80. }
  81. return v
  82. }