Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

In cases within OnRequestLimit, I want to execute next. #43

Merged
merged 2 commits into from
Dec 2, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion context.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package rl

import (
"errors"
"net/http"
"time"
)

Expand All @@ -17,11 +18,12 @@ type Context struct {
WindowLen time.Duration
RateLimitRemaining int
RateLimitReset int
Next http.Handler
Key string
lh *limitHandler
}

func newContext(statusCode int, err error, lh *limitHandler) *Context {
func newContext(statusCode int, err error, lh *limitHandler, next http.Handler) *Context {
return &Context{
StatusCode: statusCode,
Err: err,
Expand All @@ -30,6 +32,7 @@ func newContext(statusCode int, err error, lh *limitHandler) *Context {
WindowLen: lh.windowLen,
RateLimitRemaining: lh.rateLimitRemaining,
RateLimitReset: lh.rateLimitReset,
Next: next,
Key: lh.key,
lh: lh,
}
Expand Down
8 changes: 4 additions & 4 deletions rl.go
Original file line number Diff line number Diff line change
Expand Up @@ -116,23 +116,23 @@ func (lm *limitMw) Handler(next http.Handler) http.Handler {
case <-ctx.Done():
// Increment must be called even if the request limit is already exceeded
if err := lh.limiter.Increment(lh.key, currWindow); err != nil {
return newContext(http.StatusInternalServerError, err, lh)
return newContext(http.StatusInternalServerError, err, lh, next)
}
return nil
default:
}
rate, err := lh.status(now, currWindow)
if err != nil {
return newContext(http.StatusPreconditionRequired, err, lh)
return newContext(http.StatusPreconditionRequired, err, lh, next)
}
nrate := int(math.Round(rate))
if nrate >= lh.reqLimit {
return newContext(http.StatusTooManyRequests, ErrRateLimitExceeded, lh)
return newContext(http.StatusTooManyRequests, ErrRateLimitExceeded, lh, next)
}

lh.rateLimitRemaining = lh.reqLimit - nrate
if err := lh.limiter.Increment(lh.key, currWindow); err != nil {
return newContext(http.StatusInternalServerError, err, lh)
return newContext(http.StatusInternalServerError, err, lh, next)
}
return nil
})
Expand Down