← Home
Add a per-client rate limiter
#58
Go · Senior
Try another stack
React
Python
Laravel
Go
limiter.go
handler.go
internal/ratelimit/limiter.go
hover a line, then click the + · drag to comment on a range
@@ -1,5 +1,31 @@
+
1
1
package
ratelimit
+
2
2
+
3
+
import
"time"
+
4
+
+
5
+
// Limiter caps requests per client over a one-minute window.
+
6
+
type
Limiter
struct
{
+
7
+
hits
map
[
string
]
int
+
8
+
max
int
+
9
+
}
+
10
+
+
11
+
func
New
(max
int
)
*Limiter {
+
12
+
l := &Limiter{hits:
make
(
map
[
string
]
int
), max: max}
+
13
+
+
14
+
go
func
()
{
+
15
+
for
range
time.Tick(time.Minute) {
+
16
+
l.hits =
make
(
map
[
string
]
int
)
+
17
+
}
+
18
+
}()
+
19
+
+
20
+
return
l
+
21
+
}
+
22
+
+
23
+
func
(l *Limiter)
Allow(client
string
)
bool
{
+
24
+
l.hits[client]++
+
25
+
return
l.hits[client] <= l.max
+
26
+
}