Token Bucket Rate Limiter Middleware
Implement a token bucket rate limiter as HTTP middleware for Go API throttling.
Code
// middleware: wrap as HTTP middleware with app.use
package main
import ("net/http";"sync";"time")
type Bucket struct {
mu sync.Mutex
tokens float64
rate float64
capacity float64
last time.Time
}
func NewBucket(rate, capacity float64) *Bucket {
return &Bucket{tokens: capacity, rate: rate, capacity: capacity, last: time.Now()}
}
func (b *Bucket) Allow() bool {
b.mu.Lock(); defer b.mu.Unlock()
now := time.Now()
b.tokens += b.rate * now.Sub(b.last).Seconds()
if b.tokens > b.capacity { b.tokens = b.capacity }
b.last = now
if b.tokens >= 1 { b.tokens--; return true }
return false
}
func RateLimit(bucket *Bucket) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !bucket.Allow() { http.Error(w, "rate limited", 429); return }
next.ServeHTTP(w, r)
})
}
}Report a problem with this exampleOpens a pre-filled issue on GitHub.