Limit how many requests each client can make. Uses a token bucket so you get a steady rate plus short bursts. Good for protecting your API from abuse and keeping usage fair.
Full docs: Middleware Guide and Middleware Reference.
- Token bucket algorithm (smooth rate with configurable burst)
- Limit per client IP by default, or per user / custom key
- Skip specific paths (e.g. health checks)
- Standard rate limit headers: X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset
- Custom handler when the limit is exceeded
- Safe for concurrent use
go get rivaas.dev/middleware/ratelimitRequires Go 1.25 or later.
package main
import (
"net/http"
"rivaas.dev/router"
"rivaas.dev/middleware/ratelimit"
)
func main() {
r := router.New()
r.Use(ratelimit.New(
ratelimit.WithRequestsPerSecond(100),
ratelimit.WithBurst(20),
))
r.GET("/api/data", func(c *router.Context) {
c.JSON(http.StatusOK, map[string]string{"data": "value"})
})
http.ListenAndServe(":8080", r)
}| Option | What it does |
|---|---|
WithRequestsPerSecond |
Average rate (tokens per second) |
WithBurst |
Max burst size (default: same as rate) |
WithKeyFunc |
How to identify the client (default: by IP) |
WithSkipPaths |
Paths that are not rate limited |
WithOnLimitExceeded |
Custom response when limit is hit |
WithLogger |
Logger for rate limit events |
Limit per user instead of per IP:
r.Use(ratelimit.New(
ratelimit.WithRequestsPerSecond(50),
ratelimit.WithBurst(10),
ratelimit.WithKeyFunc(func(c *router.Context) string {
return basicauth.Username(c) // or from JWT, session, etc.
}),
))When a request is allowed, the middleware adds:
- X-RateLimit-Limit – Max requests in the window
- X-RateLimit-Remaining – Requests left in the current window
- X-RateLimit-Reset – When the window resets (Unix timestamp)
A runnable example is in the example/ directory:
cd example
go run main.goThen send many requests and watch the rate limit kick in.
- Middleware overview – All middleware and recommended order
- BodyLimit middleware – Limit request body size
- Timeout middleware – Limit request duration
Apache License 2.0 – see LICENSE for details.