go 51 lines · 8 steps

Per-IP rate limiting middleware in Gin

A Gin router that trusts proxy headers and throttles each client IP with its own token-bucket limiter.

Explained by highlit
1package middleware
2 
3import (
4 "log"
5 "net/http"
6 "time"
7 
8 "github.com/gin-gonic/gin"
9 "golang.org/x/time/rate"
10)
11 
12func NewRouter(trustedProxies []string) (*gin.Engine, error) {
13 r := gin.New()
14 r.Use(gin.Recovery())
15 
16 if err := r.SetTrustedProxies(trustedProxies); err != nil {
17 return nil, err
18 }
19 r.RemoteIPHeaders = []string{"X-Forwarded-For", "X-Real-IP"}
20 
21 r.Use(RateLimitByIP(rate.Every(time.Second), 20))
22 return r, nil
23}
24 
25func RateLimitByIP(r rate.Limit, burst int) gin.HandlerFunc {
26 var mu sync.Mutex
27 limiters := make(map[string]*rate.Limiter)
28 
29 get := func(ip string) *rate.Limiter {
30 mu.Lock()
31 defer mu.Unlock()
32 l, ok := limiters[ip]
33 if !ok {
34 l = rate.NewLimiter(r, burst)
35 limiters[ip] = l
36 }
37 return l
38 }
39 
40 return func(c *gin.Context) {
41 ip := c.ClientIP()
42 if !get(ip).Allow() {
43 log.Printf("rate limit exceeded for %s", ip)
44 c.AbortWithStatusJSON(http.StatusTooManyRequests, gin.H{
45 "error": "too many requests",
46 })
47 return
48 }
49 c.Next()
50 }
51}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1A closure over a shared map lets middleware keep per-key state alive across every request.
  2. 2Correctly resolving the client IP behind proxies requires configuring trusted proxies and forwarding headers.
  3. 3Guard shared mutable state with a mutex so concurrent requests can't corrupt the limiter map.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Per-IP rate limiting middleware in Gin — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code