|
| 1 | +package middlewares |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "net" |
| 6 | + "net/http" |
| 7 | + "sync" |
| 8 | + "time" |
| 9 | + |
| 10 | + "github.com/gin-gonic/gin" |
| 11 | + syncconf "github.com/sivaosorg/gocell/internal/syncConf" |
| 12 | + "github.com/sivaosorg/govm/entity" |
| 13 | + "github.com/sivaosorg/govm/logger" |
| 14 | + "github.com/sivaosorg/govm/ratelimitx" |
| 15 | + "golang.org/x/time/rate" |
| 16 | +) |
| 17 | + |
| 18 | +// https://blog.logrocket.com/rate-limiting-go-application/ |
| 19 | +type client struct { |
| 20 | + limiter *rate.Limiter |
| 21 | + last time.Time |
| 22 | +} |
| 23 | + |
| 24 | +var ( |
| 25 | + mu sync.Mutex |
| 26 | + clients = make(map[string]*client) |
| 27 | + cleanupTypeWhitelist = time.Minute |
| 28 | + cleanupWhitelist = 2 * cleanupTypeWhitelist |
| 29 | +) |
| 30 | + |
| 31 | +func (m *MiddlewareManager) RateLimitMiddleWare(key string) gin.HandlerFunc { |
| 32 | + rates := syncconf.Params.RateLimits |
| 33 | + clusters := ratelimitx.NewClusterMultiTenantRateLimitConfig().SetClusters(rates) |
| 34 | + go m.cleanupWhitelist() |
| 35 | + return func(c *gin.Context) { |
| 36 | + conf, err := clusters.FindClusterBy(key) |
| 37 | + if err != nil || !conf.Config.IsEnabled { |
| 38 | + return |
| 39 | + } |
| 40 | + ip, err := m.decodeNetwork(c) |
| 41 | + if err != nil { |
| 42 | + response := entity.NewResponseEntity().BadRequest(http.StatusText(http.StatusBadRequest), nil) |
| 43 | + response.SetError(err) |
| 44 | + c.JSON(response.StatusCode, response) |
| 45 | + c.Abort() |
| 46 | + return |
| 47 | + } |
| 48 | + mu.Lock() |
| 49 | + if _, found := clients[ip]; !found { |
| 50 | + clients[ip] = &client{limiter: rate.NewLimiter(rate.Limit(conf.Config.Rate), conf.Config.MaxBurst)} |
| 51 | + } |
| 52 | + clients[ip].last = time.Now() |
| 53 | + if !clients[ip].limiter.Allow() { |
| 54 | + mu.Unlock() |
| 55 | + response := entity.NewResponseEntity().TooManyRequest(http.StatusText(http.StatusTooManyRequests), nil) |
| 56 | + c.JSON(response.StatusCode, response) |
| 57 | + c.Abort() |
| 58 | + return |
| 59 | + } |
| 60 | + mu.Unlock() |
| 61 | + c.Next() |
| 62 | + } |
| 63 | +} |
| 64 | + |
| 65 | +func (m *MiddlewareManager) NetMiddleware() gin.HandlerFunc { |
| 66 | + return func(c *gin.Context) { |
| 67 | + ip, err := m.decodeNetwork(c) |
| 68 | + if err != nil { |
| 69 | + m.notification(c, err, http.StatusBadRequest) |
| 70 | + } |
| 71 | + logger.Debugf(fmt.Sprintf("_endpoint: %v, incoming on IP: %v", c.Request.RequestURI, ip)) |
| 72 | + c.Next() |
| 73 | + } |
| 74 | +} |
| 75 | + |
| 76 | +func (m *MiddlewareManager) decodeNetwork(c *gin.Context) (ip string, err error) { |
| 77 | + ip, _, err = net.SplitHostPort(c.Request.RemoteAddr) |
| 78 | + return ip, err |
| 79 | +} |
| 80 | + |
| 81 | +func (m *MiddlewareManager) cleanupWhitelist() { |
| 82 | + for { |
| 83 | + time.Sleep(cleanupTypeWhitelist) |
| 84 | + mu.Lock() |
| 85 | + for ip, client := range clients { |
| 86 | + remain := time.Since(client.last) |
| 87 | + if remain > cleanupWhitelist { |
| 88 | + logger.Debugf(fmt.Sprintf("Cleanup whitelist too many requests for IP: %v and remain duration: %v", ip, remain)) |
| 89 | + delete(clients, ip) |
| 90 | + } |
| 91 | + } |
| 92 | + mu.Unlock() |
| 93 | + } |
| 94 | +} |
0 commit comments