-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrate_limiter.go
More file actions
103 lines (80 loc) · 2.22 KB
/
rate_limiter.go
File metadata and controls
103 lines (80 loc) · 2.22 KB
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package main
import (
"fmt"
"log/slog"
"net"
"net/http"
"slices"
"sync"
"time"
)
type RateLimitConfig struct {
RateLimitCount int
TrustedProxies []string
}
type RateLimiter struct {
config RateLimitConfig
cache *Cache
mutex sync.RWMutex
}
func NewRateLimiter(config RateLimitConfig, cache *Cache) *RateLimiter {
return &RateLimiter{
config: config,
cache: cache,
}
}
func (rl *RateLimiter) limit(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
rl.mutex.Lock()
defer rl.mutex.Unlock()
clientIP := rl.getClientIP(r)
if clientIP == "" {
http.Error(w, "failed to determine client ip", http.StatusInternalServerError)
return
}
value, exists := rl.cache.Get(clientIP)
w.Header().Set("x-ratelimit-limit", fmt.Sprint(rl.config.RateLimitCount))
w.Header().Set("x-ratelimit-reset", fmt.Sprint(time.Now().Add(12*time.Hour).Unix()))
if !exists {
rl.cache.Set(clientIP, 1, 43200) // 12 hours TTL
w.Header().Set("x-ratelimit-remaining", fmt.Sprint(rl.config.RateLimitCount-1))
w.Header().Set("x-ratelimit-used", fmt.Sprint(1))
next.ServeHTTP(w, r)
return
}
used, ok := value.(int)
if !ok {
slog.Error("failed to assert rate limit cache value type")
http.Error(w, "internal server error", http.StatusInternalServerError)
return
}
used++
if used > rl.config.RateLimitCount {
w.Header().Set("x-ratelimit-remaining", fmt.Sprint(0))
w.Header().Set("x-ratelimit-used", fmt.Sprint(used))
http.Error(w, "rate limit exceeded", http.StatusTooManyRequests)
return
}
rl.cache.Set(clientIP, used, 43200) // 12 hours TTL
w.Header().Set("x-ratelimit-remaining", fmt.Sprint(rl.config.RateLimitCount-used))
w.Header().Set("x-ratelimit-used", fmt.Sprint(used))
next.ServeHTTP(w, r)
})
}
func (rl *RateLimiter) getClientIP(r *http.Request) string {
cfConnectingIP := r.Header.Values("cf-connecting-ip")
if len(cfConnectingIP) > 0 {
return cfConnectingIP[0]
}
ip, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
return ""
}
if slices.Contains(rl.config.TrustedProxies, ip) {
xForwardedFor := r.Header.Values("x-forwarded-for")
if len(xForwardedFor) > 0 {
return xForwardedFor[0]
}
}
return ip
}