HTTPMiddleware is an HTTP middleware that rate limits by remote IP and the request URL. The remote IP is retrieved by the X-Real-IP header. Use this middleware after webmiddleware.ProxyHeaders()
(limiter Interface, class string)
| 34 | // HTTPMiddleware is an HTTP middleware that rate limits by remote IP and the request URL. |
| 35 | // The remote IP is retrieved by the X-Real-IP header. Use this middleware after webmiddleware.ProxyHeaders() |
| 36 | func HTTPMiddleware(limiter Interface, class string) func(http.Handler) http.Handler { |
| 37 | return func(next http.Handler) http.Handler { |
| 38 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 39 | resource := httpRequestResource(r, class) |
| 40 | limit, result := limiter.RateLimit(resource) |
| 41 | result.SetHTTPHeaders(w.Header()) |
| 42 | if limit { |
| 43 | webhandlers.Error(w, r, errRateLimitExceeded.WithAttributes("key", resource.Key(), "rate", result.Limit)) |
| 44 | return |
| 45 | } |
| 46 | |
| 47 | next.ServeHTTP(w, r) |
| 48 | }) |
| 49 | } |
| 50 | } |