config.go 930 B

123456789101112131415161718192021222324252627282930313233
  1. package config
  2. import (
  3. "github.com/caarlos0/env/v9"
  4. "github.com/joho/godotenv" // 新增依赖
  5. )
  6. type Config struct {
  7. // 数据库配置
  8. DBHost string `env:"DB_HOST" envDefault:"localhost"`
  9. DBPort int `env:"DB_PORT" envDefault:"3306"`
  10. DBUser string `env:"DB_USER" envDefault:"root"`
  11. DBPassword string `env:"DB_PASSWORD" envDefault:"password"`
  12. DBName string `env:"DB_NAME" envDefault:"tasks"`
  13. //服务器配置
  14. Concurrency int `env:"CONCURRENCY" envDefault:"20"`
  15. Interval string `env:"INTERVAL" envDefault:"10m"`
  16. //日志配置
  17. LogLevel string `env:"LOG_LEVEL" envDefault:"info"`
  18. //业务配置
  19. HgApiUrl string `env:"HG_API_URL" envDefault:"https://partner.huoli.com"`
  20. }
  21. func LoadConfig() (*Config, error) {
  22. // 加载.env文件
  23. _ = godotenv.Load() // 自动从项目根目录加载.env
  24. cfg := &Config{}
  25. if err := env.Parse(cfg); err != nil {
  26. return nil, err
  27. }
  28. return cfg, nil
  29. }