limit.go 758 B

1234567891011121314151617181920212223242526272829303132
  1. // Copyright 2020 Lingfei Kong <colin404@foxmail.com>. All rights reserved.
  2. // Use of this source code is governed by a MIT style
  3. // license that can be found in the LICENSE file.
  4. package middleware
  5. import (
  6. "errors"
  7. "github.com/gin-gonic/gin"
  8. "golang.org/x/time/rate"
  9. )
  10. // ErrLimitExceeded defines Limit exceeded error.
  11. var ErrLimitExceeded = errors.New("Limit exceeded")
  12. // Limit drops (HTTP status 429) the request if the limit is reached.
  13. func Limit(maxEventsPerSec float64, maxBurstSize int) gin.HandlerFunc {
  14. limiter := rate.NewLimiter(rate.Limit(maxEventsPerSec), maxBurstSize)
  15. return func(c *gin.Context) {
  16. if limiter.Allow() {
  17. c.Next()
  18. return
  19. }
  20. // Limit reached
  21. _ = c.Error(ErrLimitExceeded)
  22. c.AbortWithStatus(429)
  23. }
  24. }