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
python
import threading from functools import wraps
A thread-safe debounce decorator in Python
decorators
debounce
threading
Advanced
6 steps
rust
use axum::{ extract::State, http::StatusCode, Json,
Idempotent webhook handling in Axum
deduplication
idempotency
shared-state
Intermediate
8 steps
php
<?php namespace App\Services;
Tagged cache invalidation in Laravel
caching
cache-tags
invalidation
Intermediate
5 steps
javascript
const crypto = require('crypto'); function inMemoryCache({ maxAge = 60_000, maxEntries = 500 } = {}) { const store = new Map();
Building an in-memory cache middleware in Express
caching
middleware
etag
Advanced
10 steps
go
func handleUpload(w http.ResponseWriter, r *http.Request) { if err := r.ParseMultipartForm(32 << 20); err != nil { http.Error(w, "failed to parse form: "+err.Error(), http.StatusBadRequest) return
Handling multi-file uploads in Go
multipart
file-upload
http-handler
Intermediate
9 steps
java
@Component public class InventoryReconciliationJob { private static final Logger log = LoggerFactory.getLogger(InventoryReconciliationJob.class);
Distributed scheduled jobs with Spring locks
distributed-locking
scheduling
concurrency
Advanced
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.