-
Notifications
You must be signed in to change notification settings - Fork 6
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
add rate limiting per X-Forwarded-For ip
Signed-off-by: Matthias Bertschy <[email protected]>
- Loading branch information
Showing
4 changed files
with
75 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
package server | ||
|
||
import ( | ||
"net/http" | ||
"sync" | ||
|
||
"github.com/didip/tollbooth/v7" | ||
"github.com/didip/tollbooth/v7/limiter" | ||
) | ||
|
||
// inspired by https://stackoverflow.com/questions/73439068/limit-max-number-of-requests-per-hour-with-didip-tollbooth | ||
|
||
type ConcurrentLimiter struct { | ||
max int | ||
current int | ||
mut sync.Mutex | ||
} | ||
|
||
func NewConcurrentLimiter(limit int) *ConcurrentLimiter { | ||
return &ConcurrentLimiter{ | ||
max: limit, | ||
} | ||
} | ||
|
||
func (limiter *ConcurrentLimiter) LimitConcurrentRequests(lmt *limiter.Limiter, | ||
handler func(http.ResponseWriter, *http.Request)) http.Handler { | ||
middle := func(w http.ResponseWriter, r *http.Request) { | ||
limiter.mut.Lock() | ||
maxHit := limiter.current == limiter.max | ||
if maxHit { | ||
limiter.mut.Unlock() | ||
http.Error(w, http.StatusText(429), http.StatusTooManyRequests) | ||
return | ||
} | ||
limiter.current += 1 | ||
limiter.mut.Unlock() | ||
defer func() { | ||
limiter.mut.Lock() | ||
limiter.current -= 1 | ||
limiter.mut.Unlock() | ||
}() | ||
// There's no rate-limit error, serve the next handler. | ||
handler(w, r) | ||
} | ||
return tollbooth.LimitHandler(lmt, http.HandlerFunc(middle)) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters