Skip to content

Commit

Permalink
Add httpate.Key(string) helper for static keys
Browse files Browse the repository at this point in the history
Useful to create compounds with a custom prefix
  • Loading branch information
VojtechVitek committed Aug 28, 2024
1 parent 5e681e3 commit cc39806
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 3 deletions.
6 changes: 6 additions & 0 deletions httprate.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,12 @@ func LimitByRealIP(requestLimit int, windowLength time.Duration) func(next http.
return Limit(requestLimit, windowLength, WithKeyFuncs(KeyByRealIP))
}

func Key(key string) func(r *http.Request) (string, error) {
return func(r *http.Request) (string, error) {
return key, nil
}
}

func KeyByIP(r *http.Request) (string, error) {
ip, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
Expand Down
4 changes: 1 addition & 3 deletions limiter.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,7 @@ func NewRateLimiter(requestLimit int, windowLength time.Duration, options ...Opt
}

if rl.keyFn == nil {
rl.keyFn = func(r *http.Request) (string, error) {
return "*", nil
}
rl.keyFn = Key("*")
}

if rl.limitCounter == nil {
Expand Down

0 comments on commit cc39806

Please sign in to comment.