Limit is a middleware to rate limit the handler
(next http.Handler)
| 122 | |
| 123 | // Limit is a middleware to rate limit the handler |
| 124 | func (rl *RateLimiter) Limit(next http.Handler) http.HandlerFunc { |
| 125 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 126 | identifier := lookupIP(r) |
| 127 | limiter := rl.getVisitor(identifier) |
| 128 | |
| 129 | if !limiter.Allow() { |
| 130 | http.Error(w, "Too many requests", http.StatusTooManyRequests) |
| 131 | log.WithFields(log.Fields{ |
| 132 | "ip": identifier, |
| 133 | }).Warn("Too many requests") |
| 134 | return |
| 135 | } |
| 136 | |
| 137 | next.ServeHTTP(w, r) |
| 138 | }) |
| 139 | } |
| 140 | |
| 141 | // ApplyLimit applies rate limit conditionally using the global limiter |
| 142 | func ApplyLimit(h http.HandlerFunc, rateLimit bool) http.Handler { |