config.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package config
  2. import (
  3. "fmt"
  4. "github.com/joho/godotenv"
  5. "github.com/spf13/viper"
  6. "os"
  7. )
  8. type Config struct {
  9. App AppConfig `yaml:"app" mapstructure:"app"`
  10. Database DatabaseConfig `yaml:"database" mapstructure:"database"`
  11. Redis RedisConfig `yaml:"redis" mapstructure:"redis"`
  12. Log LogConfig `yaml:"log" mapstructure:"log"`
  13. }
  14. type AppConfig struct {
  15. Port int `mapstructure:"port"`
  16. }
  17. type DatabaseConfig struct {
  18. Driver string `yaml:"driver" mapstructure:"driver"`
  19. Source string `yaml:"source" mapstructure:"source"`
  20. }
  21. type RedisConfig struct {
  22. Addr string `yaml:"addr" mapstructure:"addr"`
  23. Password string `yaml:"password" mapstructure:"password"`
  24. Db int `yaml:"db" mapstructure:"db"`
  25. }
  26. type LogConfig struct {
  27. Format string `yaml:"format" mapstructure:"format"`
  28. Level string `yaml:"level" mapstructure:"level"`
  29. ReportCaller bool `yaml:"reportCaller" mapstructure:"reportCaller"`
  30. }
  31. var Conf *Config
  32. // LoadConfig 加载配置文件
  33. func LoadConfig() error {
  34. // 加载 .env 文件
  35. err := godotenv.Load()
  36. if err != nil {
  37. return fmt.Errorf("加载 .env 文件失败: %v", err)
  38. }
  39. // 读取环境变量 APP_ENV
  40. env := os.Getenv("APP_ENV")
  41. if env == "" {
  42. env = "dev" // 默认环境为 dev
  43. }
  44. // 设置配置文件路径和名称
  45. viper.AddConfigPath("./configs")
  46. viper.SetConfigName(fmt.Sprintf("config_%s", env))
  47. viper.SetConfigType("yaml")
  48. // 读取配置文件
  49. err = viper.ReadInConfig()
  50. if err != nil {
  51. return fmt.Errorf("读取配置文件失败: %v", err)
  52. }
  53. // 将配置文件内容解析到 Conf 变量中
  54. Conf = &Config{}
  55. err = viper.Unmarshal(Conf)
  56. if err != nil {
  57. return fmt.Errorf("解析配置文件失败: %v", err)
  58. }
  59. return nil
  60. }