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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A closure over a shared map lets middleware keep per-key state alive across every request.
- 2Correctly resolving the client IP behind proxies requires configuring trusted proxies and forwarding headers.
- 3Guard shared mutable state with a mutex so concurrent requests can't corrupt the limiter map.
Related explainers
go
package streaming import ( "bufio"
Streaming NDJSON logs over HTTP in Go
http-streaming
channels
select
Advanced
10 steps
python
import time import uuid from django.utils.deprecation import MiddlewareMixin
Attaching per-request context in Django
middleware
request lifecycle
multi-tenancy
Intermediate
7 steps
javascript
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
go
package api import ( "crypto/sha256"
ETag conditional requests in Gin
http-caching
etag
conditional-requests
Intermediate
6 steps
go
func (w *Watcher) resetDebounce(d time.Duration) { if !w.timer.Stop() { select { case <-w.timer.C:
Debouncing a stream of events in Go
debounce
timers
channels
Advanced
7 steps
go
package logging import ( "context"
Deduplicating log attributes in Go's slog
decorator-pattern
structured-logging
immutability
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/per-ip-rate-limiting-middleware-in-gin-explained-go-80c8/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.