Guards
Guards decide whether a request proceeds. Learn the Guarder interface, the built-in ThrottlerGuard with FixedWindow, SlidingWindow, and TokenBucket strategies, and how to write custom guards.
Guards
Guards run after middleware and before interceptors. A guard inspects the incoming request and returns true to let the request proceed, or false (or panics with an exception) to reject it.
The Guarder Interface
Writing a Custom Guard
Global Guard
Apply a guard to every route in the application:
Controller-Level Guard
Handler-Level Guard
Built-in ThrottlerGuard
Ginject ships a production-grade rate limiter with three strategies.
Creating the Throttler
NewThrottler applies sensible defaults: Limit=100, TTL=1m, strategy=FixedWindow, key=client IP, backend=in-memory cache.
FixedWindow
Counts requests in fixed time buckets. Fast and simple, but allows a burst of 2× the limit at window boundaries.
SlidingWindow
Smoothly counts requests using a sliding time window. No boundary burst, more accurate than fixed window.
TokenBucket
Allows bursts up to Limit tokens, then enforces a steady refill rate. Ideal for APIs with bursty but bounded traffic.
Custom Key Function
By default, the throttler keys by client IP. Override to key by user ID, API key, or any request property:
Custom Cache Backend
Use any cache.Cache implementation as the store (e.g., Redis):
Rate Limit Response Headers
The ThrottlerGuard automatically sets:
| Header | Value |
|---|---|
X-RateLimit-Limit | The configured limit |
X-RateLimit-Remaining | Remaining requests in the window |
X-RateLimit-Reset | Unix timestamp when the window resets |
Retry-After | Seconds to wait (only on 429 Too Many Requests) |