RateLimiter
type RateLimiter struct {}RateLimiter combines a RateCounter and a PenaltyBox to provide an easy way to check whether a given entry should be rate limited given a rate window and upper limit.
Fields
RateCounter
*RateCounterPenaltyBox
*PenaltyBoxMethods
CheckRate
View sourceCheckRate increments an entry's rate counter by the delta value (RateCounter.Increment), and checks it against the provided Policy. If the count after increment exceeds the policy's MaxRate over the RateWindow, it will add the entry to the penalty box for the policy's PenaltyBoxDuration. It returns true if the entry is in the penalty box.
The limits for the delta value are the same as RateCounter.Increment.
Parameters
- entry: string
- delta: uint32
- policy: *Policy
Returns
(bool, error)
123456789101112131415161718192021222324252627fsthttp.ServeFunc(func(ctx context.Context, w fsthttp.ResponseWriter, r *fsthttp.Request) { limiter := erl.NewRateLimiter( erl.OpenRateCounter("requests"), erl.OpenPenaltyBox("bad_ips"), )
block, err := limiter.CheckRate( r.RemoteAddr, 1, &erl.Policy{ erl.RateWindow10s, 100, time.Minute, }, ) if err != nil {
log.Println("error during limit.CheckRate:", err) w.WriteHeader(fsthttp.StatusInternalServerError) return } else if block {
w.WriteHeader(fsthttp.StatusTooManyRequests) return }
})