性能优化

This commit is contained in:
xiangheng
2024-07-10 15:36:00 +08:00
parent 69fe1613fa
commit 8f42f5d33b
13 changed files with 139 additions and 75 deletions

View File

@@ -0,0 +1,29 @@
package middleware
import (
"net/http"
"time"
"github.com/gin-gonic/gin"
"go.uber.org/ratelimit"
)
// 限制每秒请求数量
// r := rg.Group("/", middleware.RateLimiterMiddleware(200))
func RateLimiterMiddleware(rate int) gin.HandlerFunc {
rl := ratelimit.New(rate)
return func(c *gin.Context) {
// Try to take a token from the rate limiter.
now := rl.Take()
// Check if we've waited longer than expected. If so, this means the rate
// limit has been exceeded.
if now.After(time.Now()) {
c.AbortWithStatus(http.StatusTooManyRequests)
return
}
c.Next()
}
}