feat: 添加限流配置层
- Config 结构体新增 RateLimit 字段 - 新增 RateLimitConfig 和 BucketConfig 结构体定义 - config.yaml 新增 ratelimit 配置段(默认关闭) - 设置默认值:query(10/0.2)、login(5/0.1)、register(3/0.05)
This commit is contained in:
@@ -10,14 +10,15 @@ import (
|
||||
|
||||
// Config 应用配置。
|
||||
type Config struct {
|
||||
App AppConfig `mapstructure:"app"`
|
||||
Server ServerConfig `mapstructure:"server"`
|
||||
Session SessionConfig `mapstructure:"session"`
|
||||
Redis RedisConfig `mapstructure:"redis"`
|
||||
AI AIConfig `mapstructure:"ai"`
|
||||
Storage StorageConfig `mapstructure:"storage"`
|
||||
Log LogConfig `mapstructure:"log"`
|
||||
Auth AuthConfig `mapstructure:"auth"`
|
||||
App AppConfig `mapstructure:"app"`
|
||||
Server ServerConfig `mapstructure:"server"`
|
||||
Session SessionConfig `mapstructure:"session"`
|
||||
Redis RedisConfig `mapstructure:"redis"`
|
||||
AI AIConfig `mapstructure:"ai"`
|
||||
Storage StorageConfig `mapstructure:"storage"`
|
||||
Log LogConfig `mapstructure:"log"`
|
||||
Auth AuthConfig `mapstructure:"auth"`
|
||||
RateLimit RateLimitConfig `mapstructure:"ratelimit"`
|
||||
}
|
||||
|
||||
// SessionConfig 会话管理配置。
|
||||
@@ -120,6 +121,20 @@ type AuthConfig struct {
|
||||
RefreshTTL int `mapstructure:"refresh_ttl"` // Refresh Token 过期时间(分钟),默认 10080(7天)
|
||||
}
|
||||
|
||||
// RateLimitConfig 限流配置。
|
||||
type RateLimitConfig struct {
|
||||
Enabled bool `mapstructure:"enabled"`
|
||||
Query BucketConfig `mapstructure:"query"`
|
||||
Login BucketConfig `mapstructure:"login"`
|
||||
Register BucketConfig `mapstructure:"register"`
|
||||
}
|
||||
|
||||
// BucketConfig 令牌桶配置。
|
||||
type BucketConfig struct {
|
||||
Capacity int `mapstructure:"capacity"` // 桶容量(突发上限)
|
||||
Rate float64 `mapstructure:"rate"` // 每秒填充令牌数
|
||||
}
|
||||
|
||||
// Load 加载配置。优先级:环境变量 > config.{env}.yaml > config.yaml > 默认值。
|
||||
// workDir 为项目根目录或 backend 目录,用于定位 .env 和 config.yaml。
|
||||
func Load(workDir string) (*Config, error) {
|
||||
@@ -218,6 +233,15 @@ func setDefaults(v *viper.Viper) {
|
||||
// log
|
||||
v.SetDefault("log.level", "info")
|
||||
v.SetDefault("log.format", "console")
|
||||
|
||||
// ratelimit
|
||||
v.SetDefault("ratelimit.enabled", false)
|
||||
v.SetDefault("ratelimit.query.capacity", 10)
|
||||
v.SetDefault("ratelimit.query.rate", 0.2)
|
||||
v.SetDefault("ratelimit.login.capacity", 5)
|
||||
v.SetDefault("ratelimit.login.rate", 0.1)
|
||||
v.SetDefault("ratelimit.register.capacity", 3)
|
||||
v.SetDefault("ratelimit.register.rate", 0.05)
|
||||
}
|
||||
|
||||
// bindEnvVars 显式绑定敏感信息环境变量。
|
||||
|
||||
Reference in New Issue
Block a user