What's Changed
- Implement rate-limiting from HTTP handler (e.g. by request payload) by @VojtechVitek in #42
- Export http.RateLimiter type by @VojtechVitek in #43
- Introduce RespondOnLimit() vs. OnLimit() methods by @VojtechVitek in #44
Add support to rate-limit by custom key from HTTP handler (e.g. by request payload fields)
// Rate-limiter for login endpoint.
loginRateLimiter := httprate.NewRateLimiter(5, time.Minute)
r.Post("/login", func(w http.ResponseWriter, r *http.Request) {
var payload struct {
Username string `json:"username"`
Password string `json:"password"`
}
err := json.NewDecoder(r.Body).Decode(&payload)
if err != nil || payload.Username == "" || payload.Password == "" {
w.WriteHeader(400)
return
}
// Rate-limit login at 5 req/min.
if loginRateLimiter.RespondOnLimit(w, r, payload.Username) {
return
}
w.Write([]byte("login at 5 req/min\n"))
})
Full Changelog: v0.12.1...v0.14.0