Files
gen2d/backend/internal/config/config.go
T

56 lines
1.4 KiB
Go
Raw Normal View History

2026-05-23 12:19:33 +08:00
// Package config 负责从环境变量加载应用配置。
package config
import (
"os"
"strconv"
)
2026-05-23 12:19:33 +08:00
// Config 应用全局配置,优先读取环境变量,未设置时使用默认值。
type Config struct {
Port int // HTTP 监听端口,默认 8080,环境变量 GEN2D_PORT
2026-05-23 12:19:33 +08:00
Mode string // Gin 运行模式 (debug/release),环境变量 GEN2D_MODE
MaxFileSize int64 // 上传文件大小上限(字节),默认 10MB
DSN string // SQLite 数据库路径,默认 data/gen2d.db,环境变量 GEN2D_DSN
JWTSecret string // JWT 签名密钥,环境变量 GEN2D_JWT_SECRET
JWTExpire int64 // JWT 过期时间(秒),默认 7200
}
2026-05-23 12:19:33 +08:00
// Load 从环境变量加载配置并返回。
func Load() *Config {
cfg := &Config{
Port: 8080,
Mode: "debug",
MaxFileSize: 10 << 20, // 10MB
DSN: "data/gen2d.db",
JWTSecret: "gen2d-dev-secret",
JWTExpire: 7200,
}
if port := os.Getenv("GEN2D_PORT"); port != "" {
if p, err := strconv.Atoi(port); err == nil {
cfg.Port = p
}
}
if mode := os.Getenv("GEN2D_MODE"); mode != "" {
cfg.Mode = mode
}
if dsn := os.Getenv("GEN2D_DSN"); dsn != "" {
cfg.DSN = dsn
}
if secret := os.Getenv("GEN2D_JWT_SECRET"); secret != "" {
cfg.JWTSecret = secret
}
if expire := os.Getenv("GEN2D_JWT_EXPIRE"); expire != "" {
if e, err := strconv.ParseInt(expire, 10, 64); err == nil {
cfg.JWTExpire = e
}
}
return cfg
}