userlimit

package
v0.0.0-...-7f6f21a Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 10, 2026 License: GPL-3.0 Imports: 9 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AsError

func AsError(r *rate.Reservation) error

AsError converts a rate.Reservation to a LimitExceededError if the rate limit is exceeded. Otherwise, it returns nil.

Types

type LimitExceededError

type LimitExceededError struct {
	// contains filtered or unexported fields
}

LimitExceededError is an error that is returned when the user has reached the limit.

func (*LimitExceededError) Delay

func (e *LimitExceededError) Delay() (time.Duration, bool)

Delay returns the delay after which the request can be retried.

func (*LimitExceededError) DelaySeconds

func (e *LimitExceededError) DelaySeconds() (int, bool)

DelaySeconds returns the delay in seconds after which the request can be retried. This is meant for the Retry-After header in HTTP responses.

func (*LimitExceededError) Error

func (e *LimitExceededError) Error() string

func (*LimitExceededError) MarshalJSON

func (e *LimitExceededError) MarshalJSON() ([]byte, error)

type UserRateLimiter

type UserRateLimiter[IDType comparable] struct {
	// contains filtered or unexported fields
}

UserRateLimiter is a rate limiter for each user. It extends x/time/rate.Limiter's capabilities.

func NewUserRateLimiter

func NewUserRateLimiter[IDType comparable](r rate.Limit, burst int) *UserRateLimiter[IDType]

NewUserRateLimiter creates a new UserRateLimiter.

func (*UserRateLimiter[IDType]) BeginCleanup

func (l *UserRateLimiter[IDType]) BeginCleanup() (stop func())

BeginCleanup starts a goroutine that cleans up unused rate limiters.

func (*UserRateLimiter[IDType]) Reserve

func (l *UserRateLimiter[IDType]) Reserve(id IDType) *rate.Reservation

Reserve is shorthand for ReserveN(time.Now(), 1).

func (*UserRateLimiter[IDType]) ReserveN

func (l *UserRateLimiter[IDType]) ReserveN(id IDType, t time.Time, n int) *rate.Reservation

ReserveN returns a Reservation that indicates how long the caller must wait before n events happen. The Limiter takes this Reservation into account when allowing future events. The returned Reservation’s OK() method returns false if n exceeds the Limiter's burst size. Usage example:

r := lim.ReserveN(time.Now(), 1)
if !r.OK() {
  // Not allowed to act! Did you remember to set lim.burst to be > 0 ?
  return
}
time.Sleep(r.Delay())
Act()

Use this method if you wish to wait and slow down in accordance with the rate limit without dropping events. If you need to respect a deadline or cancel the delay, use Wait instead. To drop or skip events exceeding rate limit, use Allow instead.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL