config.go 1.5 KB

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