config.go 1.5 KB

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