feat(login): 添加请求速率限制中间件并启用pprof锁和阻塞跟踪

This commit is contained in:
1
2025-10-24 06:04:28 +00:00
parent 18378a3ab6
commit 749b380d82
4 changed files with 27 additions and 1 deletions

View File

@@ -12,6 +12,7 @@ import (
"github.com/gogf/gf/v2/net/ghttp"
"github.com/gogf/gf/v2/os/gcmd"
"github.com/gogf/gf/v2/os/gfile"
"golang.org/x/time/rate"
)
var (
@@ -26,7 +27,7 @@ var (
}
s := g.Server()
s.Use(Limiter, ghttp.MiddlewareHandlerResponse)
s.EnableAdmin()
s.SetServerAgent(cool.Config.Name)
s.BindHookHandler("/*", ghttp.HookBeforeServe, beforeServeHook)
@@ -50,3 +51,15 @@ func beforeServeHook(r *ghttp.Request) {
//glog.Debugf(r.GetCtx(), "beforeServeHook [is file:%v] URI:%s", r.IsFileRequest(), r.RequestURI)
r.Response.CORSDefault()
}
var limiter = rate.NewLimiter(rate.Limit(10), 1)
// 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.
func Limiter(r *ghttp.Request) {
if !limiter.Allow() {
r.Response.WriteStatusExit(429) // Return 429 Too Many Requests
r.ExitAll()
}
r.Middleware.Next()
}