Skip to content

Commit

Permalink
NoCost
Browse files Browse the repository at this point in the history
  • Loading branch information
klaidliadon committed Sep 19, 2024
1 parent c32694f commit 7eaea8f
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 7 deletions.
6 changes: 6 additions & 0 deletions context.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ const (
requestLimitKey
)

const _NoLimit = -1

func WithIncrement(ctx context.Context, value int) context.Context {
return context.WithValue(ctx, incrementKey, value)
}
Expand All @@ -18,6 +20,10 @@ func getIncrement(ctx context.Context) (int, bool) {
return value, ok
}

func WithNoLimit(ctx context.Context) context.Context {
return context.WithValue(ctx, requestLimitKey, _NoLimit)
}

func WithRequestLimit(ctx context.Context, value int) context.Context {
return context.WithValue(ctx, requestLimitKey, value)
}
Expand Down
20 changes: 15 additions & 5 deletions limiter.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,22 +72,32 @@ func (l *RateLimiter) OnLimit(w http.ResponseWriter, r *http.Request, key string
currentWindow := time.Now().UTC().Truncate(l.windowLength)
ctx := r.Context()

setHeader(w, l.headers.Reset, fmt.Sprintf("%d", currentWindow.Add(l.windowLength).Unix()))

limit, ok := getRequestLimit(ctx)
if !ok {
limit = l.requestLimit
}

if limit <= 0 {
// If the limit is set to 0, we are always over limit
if limit == 0 {
return true
}
// If the limit is set to -1, we are never over limit
if limit == _NoLimit {
return false
}

setHeader(w, l.headers.Limit, fmt.Sprintf("%d", limit))
setHeader(w, l.headers.Reset, fmt.Sprintf("%d", currentWindow.Add(l.windowLength).Unix()))

increment, ok := getIncrement(r.Context())
if !ok {
increment = 1
}
// If the increment is 0, we are always on limit
if increment == 0 {
return false
}

setHeader(w, l.headers.Limit, fmt.Sprintf("%d", limit))

if increment > 1 {
setHeader(w, l.headers.Increment, fmt.Sprintf("%d", increment))
}
Expand Down
4 changes: 2 additions & 2 deletions limiter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -141,8 +141,8 @@ func TestResponseHeaders(t *testing.T) {
requestsLimit: 5,
increments: []int{0, 0, 0, 0, 0, 0},
respCodes: []int{200, 200, 200, 200, 200, 200},
respLimitHeader: []string{"5", "5", "5", "5", "5", "5"},
respRemainingHeader: []string{"5", "5", "5", "5", "5", "5"},
respLimitHeader: []string{"", "", "", "", "", ""},
respRemainingHeader: []string{"", "", "", "", "", ""},
},
{
name: "always block",
Expand Down

0 comments on commit 7eaea8f

Please sign in to comment.