@@ -66,10 +66,10 @@ type RateLimiter struct {
66
66
mu sync.Mutex
67
67
}
68
68
69
- // OnLimit checks the rate limit for the given key. If the limit is reached, it returns true
70
- // and automatically sends HTTP response. The caller should halt further request processing.
71
- // If the limit is not reached, it increments the request count and returns false, allowing
72
- // the request to proceed .
69
+ // OnLimit checks the rate limit for the given key and updates the response headers accordingly.
70
+ // If the limit is reached, it returns true, indicating that the request should be halted. Otherwise,
71
+ // it increments the request count and returns false. This method does not send an HTTP response,
72
+ // so the caller must handle the response themselves or use the RespondOnLimit() method instead .
73
73
func (l * RateLimiter ) OnLimit (w http.ResponseWriter , r * http.Request , key string ) bool {
74
74
currentWindow := time .Now ().UTC ().Truncate (l .windowLength )
75
75
ctx := r .Context ()
@@ -100,7 +100,6 @@ func (l *RateLimiter) OnLimit(w http.ResponseWriter, r *http.Request, key string
100
100
101
101
l .mu .Unlock ()
102
102
setHeader (w , l .headers .RetryAfter , fmt .Sprintf ("%d" , int (l .windowLength .Seconds ()))) // RFC 6585
103
- l .onRateLimited (w , r )
104
103
return true
105
104
}
106
105
@@ -116,6 +115,18 @@ func (l *RateLimiter) OnLimit(w http.ResponseWriter, r *http.Request, key string
116
115
return false
117
116
}
118
117
118
+ // RespondOnLimit checks the rate limit for the given key and updates the response headers accordingly.
119
+ // If the limit is reached, it automatically sends an HTTP response and returns true, signaling the
120
+ // caller to halt further request processing. If the limit is not reached, it increments the request
121
+ // count and returns false, allowing the request to proceed.
122
+ func (l * RateLimiter ) RespondOnLimit (w http.ResponseWriter , r * http.Request , key string ) bool {
123
+ onLimit := l .OnLimit (w , r , key )
124
+ if onLimit {
125
+ l .onRateLimited (w , r )
126
+ }
127
+ return onLimit
128
+ }
129
+
119
130
func (l * RateLimiter ) Counter () LimitCounter {
120
131
return l .limitCounter
121
132
}
@@ -132,7 +143,7 @@ func (l *RateLimiter) Handler(next http.Handler) http.Handler {
132
143
return
133
144
}
134
145
135
- if l .OnLimit (w , r , key ) {
146
+ if l .RespondOnLimit (w , r , key ) {
136
147
return
137
148
}
138
149
0 commit comments