zhangzengfei
2024-10-22 4ca3791590a7bf50222aa5f80e53edf04739108a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package middleware
 
import (
    "time"
 
    "gat1400Exchange/response"
 
    "github.com/gin-gonic/gin"
    "github.com/juju/ratelimit"
)
 
func RateLimitMiddleware(fillInterval time.Duration, capacity int64) gin.HandlerFunc {
    bucket := ratelimit.NewBucket(fillInterval, capacity)
    return func(c *gin.Context) {
        if bucket.TakeAvailable(1) < 1 {
            response.BadRequest(c, "访问限流")
            c.Abort()
            return
        }
        c.Next()
    }
}