config.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package config
  2. import (
  3. "flag"
  4. "fmt"
  5. "github.com/fsnotify/fsnotify"
  6. "github.com/spf13/viper"
  7. "strings"
  8. )
  9. const (
  10. DebugMode = "debug"
  11. ReleaseMode = "release"
  12. DefaultConfig = "conf/config.yaml"
  13. )
  14. type App struct {
  15. WebClient int `mapstructure:"web-client"`
  16. Register bool `mapstructure:"register"`
  17. }
  18. type Config struct {
  19. Lang string `mapstructure:"lang"`
  20. App App
  21. Gorm Gorm
  22. Mysql Mysql
  23. Gin Gin
  24. Logger Logger
  25. Redis Redis
  26. Cache Cache
  27. Oss Oss
  28. Jwt Jwt
  29. Rustdesk Rustdesk
  30. Proxy Proxy
  31. }
  32. // Init 初始化配置
  33. func Init(rowVal interface{}) *viper.Viper {
  34. var config string
  35. flag.StringVar(&config, "c", "", "choose config file.")
  36. flag.Parse()
  37. if config == "" { // 优先级: 命令行 > 默认值
  38. config = DefaultConfig
  39. }
  40. v := viper.New()
  41. v.AutomaticEnv()
  42. v.SetEnvKeyReplacer(strings.NewReplacer(".", "_", "-", "_"))
  43. v.SetEnvPrefix("RUSTDESK_API")
  44. v.SetConfigFile(config)
  45. v.SetConfigType("yaml")
  46. err := v.ReadInConfig()
  47. if err != nil {
  48. panic(fmt.Errorf("Fatal error config file: %s \n", err))
  49. }
  50. v.WatchConfig()
  51. v.OnConfigChange(func(e fsnotify.Event) {
  52. //配置文件修改监听
  53. fmt.Println("config file changed:", e.Name)
  54. if err2 := v.Unmarshal(rowVal); err2 != nil {
  55. fmt.Println(err2)
  56. }
  57. })
  58. if err := v.Unmarshal(rowVal); err != nil {
  59. fmt.Println(err)
  60. }
  61. LoadKeyFile(&rowVal.(*Config).Rustdesk)
  62. return v
  63. }
  64. // ReadEnv 读取环境变量
  65. func ReadEnv(rowVal interface{}) *viper.Viper {
  66. v := viper.New()
  67. v.AutomaticEnv()
  68. if err := v.Unmarshal(rowVal); err != nil {
  69. fmt.Println(err)
  70. }
  71. return v
  72. }