ratelimitMiddleware.go 908 B

1234567891011121314151617181920212223242526272829303132333435
  1. package middleware
  2. import (
  3. "fmt"
  4. "net/http"
  5. "perms-system-server/internal/response"
  6. "github.com/zeromicro/go-zero/core/limit"
  7. "github.com/zeromicro/go-zero/core/stores/redis"
  8. "github.com/zeromicro/go-zero/rest/httpx"
  9. )
  10. type RateLimitMiddleware struct {
  11. limiter *limit.PeriodLimit
  12. }
  13. func NewRateLimitMiddleware(rds *redis.Redis, period int, quota int, keyPrefix string) *RateLimitMiddleware {
  14. limiter := limit.NewPeriodLimit(period, quota, rds, keyPrefix)
  15. return &RateLimitMiddleware{limiter: limiter}
  16. }
  17. func (m *RateLimitMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
  18. return func(w http.ResponseWriter, r *http.Request) {
  19. ip := r.RemoteAddr
  20. key := fmt.Sprintf("ip:%s", ip)
  21. code, _ := m.limiter.Take(key)
  22. if code == limit.OverQuota {
  23. httpx.ErrorCtx(r.Context(), w, response.ErrTooManyRequests("请求过于频繁,请稍后再试"))
  24. return
  25. }
  26. next(w, r)
  27. }
  28. }