package config import ( "log" "os" "strconv" "time" "github.com/joho/godotenv" ) type Config struct { Server ServerConfig Database DatabaseConfig JWT JWTConfig ShortVideo ShortVideoConfig Qiniu QiniuConfig } 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 } // QiniuConfig 用于七牛云(Kodo)直传相关配置。 // 前端通常会向后端请求 upload token,然后直传文件到七牛。 type QiniuConfig struct { AccessKey string SecretKey string Bucket string UploadURL string CDNDomain string KeyPrefix string TokenExpireSeconds int } 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, }, Qiniu: QiniuConfig{ AccessKey: getEnv("QINIU_ACCESS_KEY", ""), SecretKey: getEnv("QINIU_SECRET_KEY", ""), Bucket: getEnv("QINIU_BUCKET", ""), UploadURL: getEnv("QINIU_UPLOAD_URL", "https://upload.qiniup.com"), CDNDomain: getEnv("QINIU_CDN_DOMAIN", ""), KeyPrefix: getEnv("QINIU_KEY_PREFIX", "uploads/"), TokenExpireSeconds: getEnvAsInt("QINIU_TOKEN_EXPIRE_SECONDS", 300), }, } } 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 }