This commit is contained in:
2025-09-12 01:15:09 +08:00
parent c563b2266b
commit e05ad9e223
103 changed files with 20034 additions and 1041 deletions

View File

@@ -34,6 +34,10 @@ type DailyRateLimitConfig struct {
BlockedCountries []string `mapstructure:"blocked_countries"` // 被阻止的国家/地区
EnableProxyCheck bool `mapstructure:"enable_proxy_check"` // 是否检查代理
MaxConcurrent int `mapstructure:"max_concurrent"` // 最大并发请求数
// 路径排除配置
ExcludePaths []string `mapstructure:"exclude_paths"` // 排除频率限制的路径
// 域名排除配置
ExcludeDomains []string `mapstructure:"exclude_domains"` // 排除频率限制的域名
}
// DailyRateLimitMiddleware 每日请求限制中间件
@@ -94,6 +98,19 @@ func (m *DailyRateLimitMiddleware) Handle() gin.HandlerFunc {
return func(c *gin.Context) {
ctx := c.Request.Context()
// 检查是否在排除路径中
if m.isExcludedPath(c.Request.URL.Path) {
c.Next()
return
}
// 检查是否在排除域名中
host := c.Request.Host
if m.isExcludedDomain(host) {
c.Next()
return
}
// 获取客户端标识
clientIP := m.getClientIP(c)
@@ -177,6 +194,64 @@ func (m *DailyRateLimitMiddleware) Handle() gin.HandlerFunc {
}
}
// isExcludedDomain 检查域名是否在排除列表中
func (m *DailyRateLimitMiddleware) isExcludedDomain(host string) bool {
for _, excludeDomain := range m.limitConfig.ExcludeDomains {
// 支持通配符匹配
if strings.HasPrefix(excludeDomain, "*") {
// 后缀匹配,如 "*.api.example.com" 匹配 "api.example.com"
if strings.HasSuffix(host, excludeDomain[1:]) {
return true
}
} else if strings.HasSuffix(excludeDomain, "*") {
// 前缀匹配,如 "api.*" 匹配 "api.example.com"
if strings.HasPrefix(host, excludeDomain[:len(excludeDomain)-1]) {
return true
}
} else {
// 精确匹配
if host == excludeDomain {
return true
}
}
}
return false
}
// isExcludedPath 检查路径是否在排除列表中
func (m *DailyRateLimitMiddleware) isExcludedPath(path string) bool {
for _, excludePath := range m.limitConfig.ExcludePaths {
// 支持多种匹配模式
if strings.HasPrefix(excludePath, "*") {
// 前缀匹配,如 "*api_name" 匹配 "/api/v1/any_api_name"
if strings.Contains(path, excludePath[1:]) {
return true
}
} else if strings.HasSuffix(excludePath, "*") {
// 后缀匹配,如 "/api/v1/*" 匹配 "/api/v1/any_api_name"
if strings.HasPrefix(path, excludePath[:len(excludePath)-1]) {
return true
}
} else if strings.Contains(excludePath, "*") {
// 中间通配符匹配,如 "/api/v1/*api_name" 匹配 "/api/v1/any_api_name"
parts := strings.Split(excludePath, "*")
if len(parts) == 2 {
prefix := parts[0]
suffix := parts[1]
if strings.HasPrefix(path, prefix) && strings.HasSuffix(path, suffix) {
return true
}
}
} else {
// 精确匹配
if path == excludePath {
return true
}
}
}
return false
}
// IsGlobal 是否为全局中间件
func (m *DailyRateLimitMiddleware) IsGlobal() bool {
return false // 不是全局中间件,需要手动应用到特定路由