-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrate_limiter.go
More file actions
110 lines (89 loc) · 2.22 KB
/
Copy pathrate_limiter.go
File metadata and controls
110 lines (89 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
104
105
106
107
108
109
110
package main
import (
"fmt"
"net"
"net/http"
"slices"
"strings"
"time"
"github.com/tinyauthapp/tinyauth/pkg/cache"
)
type RateLimitConfig struct {
RateLimitCount int
TrustedProxies []string
}
type RateLimiter struct {
config RateLimitConfig
caches struct {
ratelimit *cache.CacheStore[int]
}
}
func NewRateLimiter(config RateLimitConfig) *RateLimiter {
rl := &RateLimiter{
config: config,
}
ratelimitCache := cache.NewCacheStore[int](0)
rl.caches.ratelimit = ratelimitCache
go func() {
ticker := time.NewTicker(1 * time.Minute)
defer ticker.Stop()
for range ticker.C {
rl.caches.ratelimit.Sweep()
}
}()
return rl
}
func (rl *RateLimiter) limit(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
clientIP := rl.getClientIP(r)
if clientIP == "" {
http.Error(w, "failed to determine client ip", http.StatusInternalServerError)
return
}
var used int
rl.caches.ratelimit.WithLock(func(actions cache.CacheStoreActions[int]) {
current, exists := actions.Get(clientIP)
if !exists {
actions.Set(clientIP, 1, 12*time.Hour)
used = 1
return
}
current++
used = current
actions.Update(clientIP, current, 0)
if current > rl.config.RateLimitCount {
return
}
})
w.Header().Set("x-ratelimit-limit", fmt.Sprint(rl.config.RateLimitCount))
w.Header().Set("x-ratelimit-used", fmt.Sprint(used))
if used > rl.config.RateLimitCount {
w.Header().Set("x-ratelimit-remaining", "0")
http.Error(w, "rate limit exceeded", http.StatusTooManyRequests)
return
}
w.Header().Set("x-ratelimit-remaining", fmt.Sprint(rl.config.RateLimitCount-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.Get("x-forwarded-for")
if xForwardedFor != "" {
firstIp := strings.SplitN(xForwardedFor, ",", 2)[0]
firstIp = strings.TrimSpace(firstIp)
if firstIp != "" {
return firstIp
}
}
}
return ip
}