Skip to content

Gin

distlimit provides a native middleware adapter for Gin applications via the github.com/balramadan/distlimit/middleware/gin package.


Install Gin and distlimit using Go Modules:

Terminal window
go get github.com/gin-gonic/gin
go get github.com/balramadan/distlimit

Attach distlimit middleware globally or per-route group in your Gin router:

package main
import (
"time"
"github.com/balramadan/distlimit"
"github.com/balramadan/distlimit/algorithm/tokenbucket"
"github.com/balramadan/distlimit/driver/memory"
distlimitgin "github.com/balramadan/distlimit/middleware/gin"
"github.com/gin-gonic/gin"
)
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()),
)
r := gin.Default()
// 2. Register distlimit Middleware
r.Use(distlimitgin.New(limiter))
r.GET("/api/ping", func(c *gin.Context) {
c.JSON(200, gin.H{"message": "pong"})
})
r.Run(":8080")
}

Configure the middleware behavior by passing options into distlimitgin.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 *gin.Context) string Custom function to extract rate limit key from Gin context.
WithRouteLabeling(enable) bool Enables passing Gin full route path (c.FullPath()) into metric labels.

By default, distlimit rate limits requests based on client IP addresses. You can extract custom identifiers like API Keys or Bearer Tokens using WithKeyFunc:

r.Use(distlimitgin.New(
limiter,
distlimitgin.WithKeyFunc(func(c *gin.Context) string {
if apiKey := c.GetHeader("X-API-Key"); apiKey != "" {
return "api_key:" + apiKey
}
// Fallback to client IP address
return distlimitgin.ExtractClientIP(c, nil)
}),
))

When rate limiting is enforced, distlimit automatically injects standard RFC 6585 and legacy rate-limit headers into every Gin 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, Gin halts handler execution and returns HTTP status 429 Too Many Requests.