Documentation
¶
Overview ¶
Package ratelimit limits requests per key (token, user, IP) with GCRA, a smooth token bucket that needs one timestamp per key. The memory store fits one process; drivers/redis provides a shared one (BETA).
Middleware applies a Limiter (NewMemory or the Redis one) to a route, keyed by a KeyFunc such as ByIP or ByToken; it sets the RateLimit-* headers, answers 429 with Retry-After and denies when the limiter fails.
See https://github.com/AlexGalhardo/vukem/blob/main/docs/subsystems.md.
Example ¶
package main
import (
"fmt"
"net/http"
"net/http/httptest"
"time"
"github.com/AlexGalhardo/vukem/ratelimit"
)
func main() {
limiter := ratelimit.NewMemory(2, time.Minute)
h := ratelimit.Middleware(limiter, ratelimit.ByIP)(
http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusNoContent)
}),
)
for range 3 {
req := httptest.NewRequest(http.MethodGet, "/api/posts", http.NoBody)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
fmt.Println(rec.Code, rec.Header().Get("RateLimit-Remaining"))
}
}
Output: 204 1 204 0 429 0
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func ByToken ¶
ByToken keys requests by bearer token (hashed, never stored in clear), falling back to the client IP. Use it after authentication (auth.Required), behind an IP limit: before the token is verified, a client rotating made-up tokens gets a fresh bucket on every request.
func Middleware ¶
Middleware limits requests with l, keyed by key (ByIP when nil). It sets RateLimit-Limit/Remaining/Reset on every response and answers 429 with Retry-After when the bucket is empty. A failing limiter denies the request (fail closed).