Fiber v3
distlimit provides a native, zero-dependency middleware adapter for Fiber v3 applications via the github.com/balramadan/distlimit/middleware/fiber package.
Installation
Section titled “Installation”Install Fiber v3 and distlimit using Go Modules:
go get github.com/gofiber/fiber/v3go get github.com/balramadan/distlimitBasic Setup
Section titled “Basic Setup”Attach distlimit middleware globally to your Fiber application instance:
package main
import ( "time"
"github.com/balramadan/distlimit" "github.com/balramadan/distlimit/algorithm/tokenbucket" "github.com/balramadan/distlimit/driver/memory" distlimitfiber "github.com/balramadan/distlimit/middleware/fiber" "github.com/gofiber/fiber/v3")
func main() { // 1. Initialize Driver & Limiter (100 requests / minute) memDriver := memory.New(5 * time.Minute) limiter, _ := distlimit.New( memDriver, distlimit.WithLimit(100), distlimit.WithWindow(1*time.Minute), distlimit.WithAlgorithm(tokenbucket.New()), )
app := fiber.New()
// 2. Register distlimit Middleware app.Use(distlimitfiber.New(limiter))
app.Get("/api/ping", func(c fiber.Ctx) error { return c.SendString("pong") })
app.Listen(":3000")}Configuration Options
Section titled “Configuration Options”Configure the middleware behavior by passing options into distlimitfiber.New(limiter, opts...):
| Option | Type | Description |
|---|---|---|
WithTrustedProxies(proxies) |
[]string |
CIDR blocks or IPs of trusted reverse proxies for secure IP parsing. |
WithKeyFunc(fn) |
func(c fiber.Ctx) string |
Custom function to extract rate limit key from Fiber context. |
WithRouteLabeling(enable) |
bool |
Enables passing Fiber route path (c.Route().Path) into metric labels. |
Custom Key Extraction Example
Section titled “Custom Key Extraction Example”By default, distlimit rate limits requests based on client IP addresses. You can extract custom identifiers like API Keys or Bearer Tokens using WithKeyFunc:
app.Use(distlimitfiber.New( limiter, distlimitfiber.WithKeyFunc(func(c fiber.Ctx) string { if apiKey := c.Get("X-API-Key"); apiKey != "" { return "api_key:" + apiKey } // Fallback to client IP address return distlimitfiber.ExtractClientIP(c, nil) }),))Response Headers & Error Behavior
Section titled “Response Headers & Error Behavior”When rate limiting is enforced, distlimit automatically injects standard RFC 6585 and legacy rate-limit headers into every Fiber HTTP response:
| Header | Description | Example |
|---|---|---|
RateLimit-Limit |
Configured maximum request quota in current window | 100 |
RateLimit-Remaining |
Remaining allowed requests in current window | 99 |
RateLimit-Reset |
Time in seconds until request quota resets | 45 |
X-RateLimit-Limit |
Legacy header for maximum request limit | 100 |
X-RateLimit-Remaining |
Legacy header for remaining request quota | 99 |
X-RateLimit-Reset |
Legacy header for reset duration in seconds | 45 |
When a client exceeds the allowed quota, Fiber halts execution and returns HTTP status 429 Too Many Requests.