ratelimit

package module
v0.0.0-...-517e9f2 Latest Latest
Warning

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

Go to latest
Published: Apr 6, 2026 License: MIT Imports: 10 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrRateLimitExceeded = keratin.NewHTTPError(http.StatusTooManyRequests, "Rate limit exceeded.")

ErrRateLimitExceeded denotes an error raised when a rate limit is exceeded

Functions

func Middleware

func Middleware(limiter *Limiter, skippers ...middleware.Skipper) func(http.Handler) http.Handler

Types

type Config

type Config struct {
	// TimestampFunc return current unix timestamp (seconds)
	// max value is 4294967295 -> Sun Feb 07 2106 06:28:15 GMT+0000
	//
	// Default: func() uint32 {
	//   return uint32(time.Now().Unix())
	// }
	TimestampFunc func() uint32 `json:"-" yaml:"-"`

	// IdentifierExtractor uses http.Request to extract the identifier, by a default req.RemoteAddr is used
	//
	// Default: func(req *http.Request) string {
	//   return req.RemoteAddr
	// }
	IdentifierExtractor func(*http.Request) (string, error) `json:"-" yaml:"-"`

	// Max number of recent connections during `Expiration` seconds before sending a 429 response
	//
	// Default: 5
	Max uint `env:"MAX" json:"max,omitempty" yaml:"max,omitempty"`

	// MaxFunc a function to dynamically calculate the max requests supported by the rate limiter middleware
	//
	// Default: func(*http.Request) int {
	//   return c.Max
	// }
	MaxFunc func(*http.Request) uint `json:"-" yaml:"-"`

	// Expiration is the time on how long to keep records of requests in memory
	//
	// Default: 1 * time.Minute
	Expiration time.Duration `env:"EXPIRATION" json:"expiration,omitempty,format:units" yaml:"expiration,omitempty"`

	// ExpirationFunc a function to dynamically calculate the expiration supported by the rate limiter middleware
	//
	// Default: func(*http.Request) time.Duration {
	//   return c.Expiration
	// }
	ExpirationFunc func(*http.Request) time.Duration `json:"-" yaml:"-"`

	// When set to true, the middleware will not include the rate limit headers (X-RateLimit-* and Retry-After) in the response.
	//
	// Default: false
	DisableHeaders bool `env:"DISABLE_HEADERS" json:"disableHeaders,omitempty" yaml:"disableHeaders,omitempty"`

	// DisableValueRedaction turns off masking limiter keys in logs and error messages when set to true.
	//
	// Default: false
	DisableValueRedaction bool `env:"DISABLE_VALUE_REDACTION" json:"disableValueRedaction,omitempty" yaml:"disableValueRedaction,omitempty"`
}

func (*Config) SetDefaults

func (c *Config) SetDefaults()

type Limiter

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

Limiter implements the sliding-window rate limiting strategy

func NewLimiter

func NewLimiter(cfg Config) *Limiter

func NewLimiterWithStorage

func NewLimiterWithStorage(cfg Config, storage Storage) *Limiter

func (*Limiter) Allow

func (l *Limiter) Allow(w http.ResponseWriter, r *http.Request) error

type MemoryStorage

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

func NewMemoryStorage

func NewMemoryStorage(timestampFunc func() uint32) *MemoryStorage

func (*MemoryStorage) Get

func (s *MemoryStorage) Get(_ context.Context, key string) ([]byte, error)

Get retrieves the value stored under key, returning nil when the entry does not exist or has expired.

For []byte values, this returns a defensive copy to prevent callers from mutating the stored data. Other types are returned as-is.

func (*MemoryStorage) Set

func (s *MemoryStorage) Set(_ context.Context, key string, val []byte, ttl time.Duration) error

Set stores val under key and applies the optional ttl before expiring the entry. A non-positive ttl keeps the item forever.

String keys are defensively copied to prevent corruption from pooled buffers. []byte values are also copied to prevent external mutation of stored data. Other types are stored as-is (structs are copied by value automatically).

type Storage

type Storage interface {
	// Get gets the value for the given key with a context.
	// `nil, nil` is returned when the key does not exist
	Get(ctx context.Context, key string) ([]byte, error)

	// Set stores the given value for the given key with an expiration value.
	Set(ctx context.Context, key string, value []byte, exp time.Duration) error
}

Storage is used to store the state of Limiter

Jump to

Keyboard shortcuts

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