feat: 添加限流触发日志
This commit is contained in:
@@ -5,6 +5,8 @@ import (
|
|||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
|
|
||||||
|
"github.com/hhs/camtalk/internal/trace"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Middleware 返回 Gin 中间件,按 key 维度限流。
|
// Middleware 返回 Gin 中间件,按 key 维度限流。
|
||||||
@@ -26,6 +28,13 @@ func Middleware(limiter Limiter, keyFunc func(*gin.Context) string) gin.HandlerF
|
|||||||
allowed, retryAfter := limiter.Allow(c.Request.Context(), key)
|
allowed, retryAfter := limiter.Allow(c.Request.Context(), key)
|
||||||
|
|
||||||
if !allowed {
|
if !allowed {
|
||||||
|
log := trace.FromContext(c.Request.Context())
|
||||||
|
log.Warnw("rate limited",
|
||||||
|
"client_ip", c.ClientIP(),
|
||||||
|
"path", c.Request.URL.Path,
|
||||||
|
"limit_key", key,
|
||||||
|
"retry_after_sec", int(retryAfter.Seconds()+0.5))
|
||||||
|
|
||||||
// 设置 Retry-After header(秒)
|
// 设置 Retry-After header(秒)
|
||||||
c.Header("Retry-After", fmt.Sprintf("%d", int(retryAfter.Seconds()+0.5)))
|
c.Header("Retry-After", fmt.Sprintf("%d", int(retryAfter.Seconds()+0.5)))
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user