config.go 1.6 KB

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