package main import ( "sync" "time" ) // RateLimiter is a fixed-window per-key request limiter: at most max // requests per key within each window. Keys are client IPs. It is the // "max requests per minute" anti-abuse guard; excess requests are denied // until the current window rolls over. State is in memory only. type RateLimiter struct { mu sync.Mutex max int window time.Duration visitors map[string]*visitor lastGC time.Time } type visitor struct { count int resetAt time.Time } func NewRateLimiter(max int, window time.Duration) *RateLimiter { if max < 1 { max = 1 } if window <= 0 { window = time.Minute } return &RateLimiter{max: max, window: window, visitors: make(map[string]*visitor)} } // Allow reports whether key may make one more request. If not, it returns // how long the caller should wait before retrying. func (rl *RateLimiter) Allow(key string) (bool, time.Duration) { rl.mu.Lock() defer rl.mu.Unlock() now := time.Now() v, ok := rl.visitors[key] if !ok || now.After(v.resetAt) { v = &visitor{count: 0, resetAt: now.Add(rl.window)} rl.visitors[key] = v } if now.Sub(rl.lastGC) > rl.window { for k, e := range rl.visitors { if now.After(e.resetAt) { delete(rl.visitors, k) } } rl.lastGC = now } if v.count >= rl.max { return false, time.Until(v.resetAt) } v.count++ return true, 0 }