config.go 1.6 KB

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