Skip to content

Commit

Permalink
Merge pull request #5 from k1LoW/fix-interface-more
Browse files Browse the repository at this point in the history
Re-change the interface of Limiter.
  • Loading branch information
k1LoW authored Aug 27, 2023
2 parents f46ae32 + df7da4f commit 79e7333
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 6 deletions.
10 changes: 5 additions & 5 deletions rl.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ type Limiter interface {
Name() string
// KeyAndRateLimit returns the key and rate limit for the request
KeyAndRateLimit(r *http.Request) (key string, reqLimit int, windowLen time.Duration, err error)
// IsXRateLimitHeadersRequired returns true if the X-RateLimit headers are required
IsXRateLimitHeadersRequired(err error) bool
// ShouldSetXRateLimitHeaders returns true if the X-RateLimit-* headers should be set
ShouldSetXRateLimitHeaders(err error) bool
// OnRequestLimit returns the handler to be called when the rate limit is exceeded
OnRequestLimit() http.HandlerFunc

Expand Down Expand Up @@ -117,14 +117,14 @@ func (rl *rateLimiter) Handler(next http.Handler) http.Handler {
if err := eg.Wait(); err != nil {
// Handle first error
if e, ok := err.(*LimitError); ok {
if e.lh.limiter.IsXRateLimitHeadersRequired(err) {
if e.lh.limiter.ShouldSetXRateLimitHeaders(err) {
w.Header().Set("X-RateLimit-Limit", fmt.Sprintf("%d", e.lh.reqLimit))
w.Header().Set("X-RateLimit-Remaining", fmt.Sprintf("%d", e.lh.rateLimitRemaining))
w.Header().Set("X-RateLimit-Reset", fmt.Sprintf("%d", e.lh.rateLimitReset))
}
if errors.Is(e.err, ErrRateLimitExceeded) {
// Rate limit exceeded
if e.lh.limiter.IsXRateLimitHeadersRequired(err) {
if e.lh.limiter.ShouldSetXRateLimitHeaders(err) {
w.Header().Set("Retry-After", fmt.Sprintf("%d", int(e.lh.windowLen.Seconds()))) // RFC 6585
}
e.lh.limiter.OnRequestLimit()(w, r)
Expand All @@ -139,7 +139,7 @@ func (rl *rateLimiter) Handler(next http.Handler) http.Handler {

if len(lhs) > 0 {
// Set X-RateLimit-* headers using the first limiter
if lhs[0].limiter.IsXRateLimitHeadersRequired(nil) {
if lhs[0].limiter.ShouldSetXRateLimitHeaders(nil) {
w.Header().Set("X-RateLimit-Limit", fmt.Sprintf("%d", lhs[0].reqLimit))
w.Header().Set("X-RateLimit-Remaining", fmt.Sprintf("%d", lhs[0].rateLimitRemaining))
w.Header().Set("X-RateLimit-Reset", fmt.Sprintf("%d", lhs[0].rateLimitReset))
Expand Down
2 changes: 1 addition & 1 deletion testutil/limiter.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ func (l *Limiter) KeyAndRateLimit(r *http.Request) (string, int, time.Duration,
return key, l.reqLimit, time.Second, nil
}

func (l *Limiter) IsXRateLimitHeadersRequired(err error) bool {
func (l *Limiter) ShouldSetXRateLimitHeaders(err error) bool {
return true
}

Expand Down

0 comments on commit 79e7333

Please sign in to comment.