config.go 845 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. package config
  2. import (
  3. "fmt"
  4. "github.com/spf13/viper"
  5. "os"
  6. "time"
  7. )
  8. type Config struct {
  9. Redis struct {
  10. Addr string `mapstructure:"addr"`
  11. Password string `mapstructure:"password"`
  12. DB int `mapstructure:"db"`
  13. ReadTimeout time.Duration `mapstructure:"read_timeout"`
  14. WriteTimeout time.Duration `mapstructure:"write_timeout"`
  15. } `mapstructure:"redis"`
  16. RabbitMQ struct {
  17. URL string `mapstructure:"url"`
  18. } `mapstructure:"rabbitmq"`
  19. }
  20. func NewConfig(p string) *viper.Viper {
  21. envConf := os.Getenv("APP_CONF")
  22. if envConf == "" {
  23. envConf = p
  24. }
  25. fmt.Println("load conf file:", envConf)
  26. return getConfig(envConf)
  27. }
  28. func getConfig(path string) *viper.Viper {
  29. conf := viper.New()
  30. conf.SetConfigFile(path)
  31. err := conf.ReadInConfig()
  32. if err != nil {
  33. panic(err)
  34. }
  35. return conf
  36. }