package config import ( "log" "os" "strconv" "time" "github.com/joho/godotenv" ) type Config struct { Server ServerConfig Database DatabaseConfig JWT JWTConfig ShortVideo ShortVideoConfig } type ServerConfig struct { Port string Mode string } type DatabaseConfig struct { Host string Port string User string Password string DBName string } type JWTConfig struct { Secret string Expire int } type ShortVideoConfig struct { APIKey string FreeDailyQuota int RequestTimeout time.Duration } var AppConfig *Config func LoadConfig() { // 加载 .env 文件 if err := godotenv.Load(); err != nil { log.Println("未找到 .env 文件,使用环境变量") } AppConfig = &Config{ Server: ServerConfig{ Port: getEnv("SERVER_PORT", "8080"), Mode: getEnv("GIN_MODE", "debug"), }, Database: DatabaseConfig{ Host: getEnv("DB_HOST", "localhost"), Port: getEnv("DB_PORT", "3306"), User: getEnv("DB_USER", "root"), Password: getEnv("DB_PASSWORD", ""), DBName: getEnv("DB_NAME", "wx_service"), }, JWT: JWTConfig{ Secret: getEnv("JWT_SECRET", "your-secret-key"), Expire: 86400, // 24小时 }, ShortVideo: ShortVideoConfig{ APIKey: getEnv("SHORT_VIDEO_API_KEY", ""), FreeDailyQuota: getEnvAsInt("SHORT_VIDEO_FREE_QUOTA", 20), RequestTimeout: time.Duration(getEnvAsInt("SHORT_VIDEO_TIMEOUT_SECONDS", 5)) * time.Second, }, } } func getEnv(key, defaultValue string) string { if value := os.Getenv(key); value != "" { return value } return defaultValue } func getEnvAsInt(key string, defaultValue int) int { if value := os.Getenv(key); value != "" { if v, err := strconv.Atoi(value); err == nil { return v } } return defaultValue }