summaryrefslogtreecommitdiff
path: root/ratelimit.go
diff options
context:
space:
mode:
authorSebastian Zack Tin Lahm-Lee <bctnry@sdf.org>2026-10-04 12:58:12 +0800
committerSebastian Zack Tin Lahm-Lee <bctnry@sdf.org>2026-10-04 12:58:12 +0800
commit78b410c668354c30323a259167beb7eddaa2d58f (patch)
treeb45dc58e106686deba0c71ac65572ccc9d29f0af /ratelimit.go
first verHEADmaster
Diffstat (limited to 'ratelimit.go')
-rw-r--r--ratelimit.go59
1 files changed, 59 insertions, 0 deletions
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
+}