-
Notifications
You must be signed in to change notification settings - Fork 0
/
ratelimit.go
56 lines (50 loc) · 1.32 KB
/
ratelimit.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package gin
import (
"fmt"
"github.com/gin-gonic/gin"
"net/http"
"sync/atomic"
"time"
"github.com/vnroyalclub/kratos/pkg/log"
limit "github.com/vnroyalclub/kratos/pkg/ratelimit"
"github.com/vnroyalclub/kratos/pkg/ratelimit/bbr"
)
// RateLimiter bbr middleware.
type RateLimiter struct {
group *bbr.Group
logTime int64
}
// NewRateLimiter return a ratelimit middleware.
func NewRateLimiter(conf *bbr.Config) (s *RateLimiter) {
return &RateLimiter{
group: bbr.NewGroup(conf),
logTime: time.Now().UnixNano(),
}
}
func (b *RateLimiter) printStats(routePath string, limiter limit.Limiter) {
now := time.Now().UnixNano()
if now-atomic.LoadInt64(&b.logTime) > int64(time.Second*3) {
atomic.StoreInt64(&b.logTime, now)
log.Info("http.bbr path:%s stat:%+v", routePath, limiter.(*bbr.BBR).Stat())
}
}
// Limit return a bm handler func.
func (b *RateLimiter) Limit() gin.HandlerFunc {
return func(c *gin.Context) {
uri := fmt.Sprintf("%s://%s%s", c.Request.URL.Scheme, c.Request.Host, c.Request.URL.Path)
limiter := b.group.Get(uri)
done, err := limiter.Allow(c)
if err != nil {
_metricServerBBR.Inc(uri, c.Request.Method)
res := TOJSON(nil, err)
c.JSON(http.StatusOK, res)
c.Abort()
return
}
defer func() {
done(limit.DoneInfo{Op: limit.Success})
b.printStats(uri, limiter)
}()
c.Next()
}
}