Files
goods/api/internal/adminhandler/ratelimit.go
T
fu500fandDevin AI 31e1a8977b fix(api): 清理投稿限流器的过期 IP 记录 (#44)
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-31 00:52:56 +00:00

60 lines
1.3 KiB
Go

package adminhandler
import (
"sync"
"time"
)
// rateLimiter is a simple fixed-window per-key limiter used to throttle
// anonymous public submissions (basic anti-spam; captcha can be added later).
type rateLimiter struct {
mu sync.Mutex
hits map[string][]time.Time
limit int
window time.Duration
lastPrune time.Time
}
func newRateLimiter(limit int, window time.Duration) *rateLimiter {
return &rateLimiter{hits: map[string][]time.Time{}, limit: limit, window: window}
}
// allow reports whether the key may proceed, recording the hit if so.
func (r *rateLimiter) allow(key string) bool {
now := time.Now()
cutoff := now.Add(-r.window)
r.mu.Lock()
defer r.mu.Unlock()
if now.Sub(r.lastPrune) > r.window {
for expiredKey, hits := range r.hits {
kept := pruneRateLimitHits(hits, cutoff)
if len(kept) == 0 {
delete(r.hits, expiredKey)
} else {
r.hits[expiredKey] = kept
}
}
r.lastPrune = now
}
kept := pruneRateLimitHits(r.hits[key], cutoff)
if len(kept) >= r.limit {
r.hits[key] = kept
return false
}
r.hits[key] = append(kept, now)
return true
}
func pruneRateLimitHits(hits []time.Time, cutoff time.Time) []time.Time {
kept := hits[:0]
for _, hit := range hits {
if hit.After(cutoff) {
kept = append(kept, hit)
}
}
return kept
}