From cc398060a31870355497226f798eccdc762f0732 Mon Sep 17 00:00:00 2001 From: Vojtech Vitek Date: Wed, 28 Aug 2024 20:04:29 +0200 Subject: [PATCH] Add httpate.Key(string) helper for static keys Useful to create compounds with a custom prefix --- httprate.go | 6 ++++++ limiter.go | 4 +--- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/httprate.go b/httprate.go index 96ff4bf..75a438d 100644 --- a/httprate.go +++ b/httprate.go @@ -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 { diff --git a/limiter.go b/limiter.go index dc69002..d5ef436 100644 --- a/limiter.go +++ b/limiter.go @@ -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 {