From 78b410c668354c30323a259167beb7eddaa2d58f Mon Sep 17 00:00:00 2001 From: Sebastian Zack Tin Lahm-Lee Date: Sun, 4 Oct 2026 12:58:12 +0800 Subject: first ver --- ratelimit.go | 59 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 ratelimit.go (limited to 'ratelimit.go') diff --git a/ratelimit.go b/ratelimit.go new file mode 100644 index 0000000..b088fbc --- /dev/null +++ b/ratelimit.go @@ -0,0 +1,59 @@ +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 +} -- cgit v1.2.3