```
All checks were successful
ci/woodpecker/push/my-first-workflow Pipeline was successful

feat(login): 添加限流功能并更新依赖

- 引入 github.com/yudeguang/ratelimit 库替代原有的 golang.org/x/time/rate
- 实现基于IP地址的访问频率限制
- 添加每秒20次请求的限流规则
- 更新 go.mod 和 go.sum 文件以包含新依赖项
```
This commit is contained in:
昔念
2026-01-30 01:30:46 +08:00
parent 51174479ad
commit d07f04bafc
3 changed files with 22 additions and 5 deletions

View File

@@ -1,9 +1,11 @@
package cmd
import (
"context"
"blazing/cool"
"context"
"time"
"github.com/yudeguang/ratelimit"
i18n "blazing/modules/base/middleware"
@@ -12,7 +14,6 @@ import (
"github.com/gogf/gf/v2/os/gcmd"
"github.com/gogf/gf/v2/os/gfile"
"github.com/xiaoqidun/qqwry"
"golang.org/x/time/rate"
)
var (
@@ -62,7 +63,17 @@ func beforeServeHook(r *ghttp.Request) {
r.Response.CORSDefault()
}
var limiter = rate.NewLimiter(rate.Limit(150), 50)
// var limiter = rate.NewLimiter(rate.Limit(150), 50)
var limiter *ratelimit.Rule = ratelimit.NewRule()
// 简单规则案例
func init() {
//步骤二:增加一条或者多条规则组成复合规则,此复合规则必须至少包含一条规则
limiter.AddRule(time.Second*1, 20)
//步骤三:调用函数判断某用户是否允许访问 allow:= r.AllowVisit(user)
}
// Limiter is a middleware that implements rate limiting for all HTTP requests.
// It returns HTTP 429 (Too Many Requests) when the rate limit is exceeded.
@@ -71,7 +82,7 @@ func Limiter(r *ghttp.Request) {
// - rate.Limit(2): 表示速率为 "每秒2个请求"
// - 2: 表示桶的容量 (Burst)允许瞬时处理2个请求
if !limiter.Allow() {
if !limiter.AllowVisitByIP4(r.GetClientIp()) {
r.Response.WriteStatusExit(429) // Return 429 Too Many Requests
r.ExitAll()
}