File tree Expand file tree Collapse file tree 1 file changed +7
-11
lines changed
internal/transport/http/ratelimit Expand file tree Collapse file tree 1 file changed +7
-11
lines changed Original file line number Diff line number Diff line change 3
3
package ratelimit
4
4
5
5
import (
6
- "log/slog"
7
- "net"
8
6
"net/http"
9
7
"sync"
10
8
"time"
@@ -54,10 +52,12 @@ func (r *rateLimiter) getVisitor(ip visitorIP) *rate.Limiter {
54
52
55
53
v , exists := r .visitors [ip ]
56
54
if ! exists {
55
+ limit := rate .NewLimiter (r .limit , r .burst )
57
56
r .visitors [ip ] = & visitor {
58
- limiter : rate . NewLimiter ( 1 , 1 ) ,
57
+ limiter : limit ,
59
58
lastSeen : time .Now (),
60
59
}
60
+ return limit
61
61
}
62
62
63
63
v .lastSeen = time .Now ()
@@ -97,17 +97,13 @@ func MiddlewareWithConfig(c Config) gin.HandlerFunc {
97
97
go lmt .cleanupVisitors ()
98
98
99
99
return func (c * gin.Context ) {
100
- ip , _ , err := net .SplitHostPort (c .Request .RemoteAddr )
101
- if err != nil {
102
- slog .Error ("splitting host and port" , "err" , err )
103
- c .AbortWithStatusJSON (
104
- http .StatusInternalServerError ,
105
- gin.H {"message" : "internal server error" },
106
- )
100
+ visitor := lmt .getVisitor (visitorIP (c .ClientIP ()))
101
+ if visitor == nil {
102
+ c .AbortWithStatus (http .StatusInternalServerError )
107
103
return
108
104
}
109
105
110
- if ! lmt . getVisitor ( visitorIP ( ip )) .Allow () {
106
+ if ! visitor .Allow () {
111
107
c .AbortWithStatus (http .StatusTooManyRequests )
112
108
return
113
109
}
You can’t perform that action at this time.
0 commit comments