Files
flatrender/services/gateway/internal/middleware/rate_limiter.go
T
soroush.asadi 90ac0b81d1 feat: V2 microservices stack — backend services, gateway, JWT auth
Add full V2 architecture: identity, content, studio (.NET 10) and file,
render, notification, gateway (Go) services with vendored deps, plus DB
migrations, event/API contracts, and an init-db script.

Wire the Next.js frontend to the gateway: server-side JWT auth routes
(login/register/refresh/logout/me), gateway fetch helper, and session/
cookie/jwt helpers under src/lib.

Containerize the stack via docker-compose.v2.yml and per-service
Dockerfiles. Base images resolve through a Nexus mirror (Docker Hub) and
MCR directly; npm/NuGet pull from Nexus groups. Self-host fonts via
next/font/local to avoid Google Fonts (geo-blocked).

Add CI workflow and ignore .env.v2, *.stackdump, and .NET bin/obj.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-29 23:29:31 +03:30

95 lines
2.0 KiB
Go

package middleware
import (
"net/http"
"sync"
"time"
"github.com/gin-gonic/gin"
)
// ipBucket is a per-IP sliding-window counter.
type ipBucket struct {
mu sync.Mutex
times []time.Time
limit int
window time.Duration
}
func (b *ipBucket) allow() bool {
b.mu.Lock()
defer b.mu.Unlock()
now := time.Now()
cutoff := now.Add(-b.window)
// Evict timestamps outside the window
valid := b.times[:0]
for _, t := range b.times {
if t.After(cutoff) {
valid = append(valid, t)
}
}
b.times = valid
if len(b.times) >= b.limit {
return false
}
b.times = append(b.times, now)
return true
}
// RateLimiter is a per-IP sliding-window rate limiter backed by sync.Map.
// It is safe for concurrent use and cleans up idle buckets automatically.
type RateLimiter struct {
buckets sync.Map // string(ip) → *ipBucket
limit int
window time.Duration
}
// NewRateLimiter creates a limiter that allows up to limit requests per window
// per IP address.
func NewRateLimiter(limit int, window time.Duration) *RateLimiter {
rl := &RateLimiter{limit: limit, window: window}
go rl.gc()
return rl
}
// gc periodically removes buckets that have had no activity for one full window.
func (rl *RateLimiter) gc() {
ticker := time.NewTicker(rl.window)
defer ticker.Stop()
for range ticker.C {
rl.buckets.Range(func(k, v any) bool {
b := v.(*ipBucket)
b.mu.Lock()
if len(b.times) == 0 {
rl.buckets.Delete(k)
}
b.mu.Unlock()
return true
})
}
}
// Middleware returns a gin.HandlerFunc that enforces the rate limit.
func (rl *RateLimiter) Middleware() gin.HandlerFunc {
return func(c *gin.Context) {
ip := c.ClientIP()
v, _ := rl.buckets.LoadOrStore(ip, &ipBucket{
times: make([]time.Time, 0, rl.limit),
limit: rl.limit,
window: rl.window,
})
b := v.(*ipBucket)
if !b.allow() {
c.AbortWithStatusJSON(http.StatusTooManyRequests, gin.H{
"code": "rate_limited",
"message": "too many requests — slow down",
})
return
}
c.Next()
}
}