1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
|
package middleware
import (
"net/http"
"slices"
"sync"
"time"
"github.com/adrian-lorenz/noxway/global"
"github.com/gin-gonic/gin"
)
type RateLimiterConfig struct {
Rate int
Window time.Duration
}
type RequestCounter struct {
Count int
LastRequest time.Time
}
// rateLimiter speichert die Anfragenzähler für jede IP
var rateLimiter = make(map[string]*RequestCounter)
var rateMu sync.Mutex
var cleanupOnce sync.Once
// startCleanup starts a background goroutine that periodically removes stale entries
func startCleanup(window time.Duration) {
cleanupOnce.Do(func() {
go func() {
ticker := time.NewTicker(window)
defer ticker.Stop()
for range ticker.C {
cleanupStaleEntries(window)
}
}()
})
}
// cleanupStaleEntries removes entries that haven't been accessed within the window
func cleanupStaleEntries(window time.Duration) {
rateMu.Lock()
defer rateMu.Unlock()
now := time.Now()
for ip, counter := range rateLimiter {
if now.Sub(counter.LastRequest) > window {
delete(rateLimiter, ip)
}
}
}
func RateLimiterMiddleware(config RateLimiterConfig) gin.HandlerFunc {
// Start cleanup goroutine
startCleanup(config.Window)
return func(c *gin.Context) {
ip := GetIP(c)
if slices.Contains(global.Config.RateWhitelist, ip) {
c.Next()
return
}
rateMu.Lock()
defer rateMu.Unlock()
counter, exists := rateLimiter[ip]
if !exists {
counter = &RequestCounter{}
rateLimiter[ip] = counter
}
now := time.Now()
if now.Sub(counter.LastRequest) > config.Window {
counter.Count = 0
counter.LastRequest = now
}
if counter.Count >= config.Rate {
c.AbortWithStatusJSON(http.StatusTooManyRequests, gin.H{"error": "Rate limit exceeded"})
return
}
counter.Count++
counter.LastRequest = now
c.Next()
}
}
|