ratelimit

package
v0.9.0 Latest Latest
Warning

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

Go to latest
Published: Apr 29, 2026 License: BSD-2-Clause Imports: 7 Imported by: 0

Documentation

Overview

Package ratelimit provides tiered HTTP rate limiting middleware.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ExtractIP

func ExtractIP(r *http.Request) string

ExtractIP gets client ip from request, checking X-Forwarded-For, X-Real-IP, then RemoteAddr

Types

type Config

type Config struct {
	Tiers            map[Tier]TierConfig
	KeyExtractor     KeyExtractor
	TierResolver     TierResolver
	EventHandler     EventHandler
	CleanupInterval  time.Duration
	WarningThreshold float64 // fires OnApproaching when remaining tokens fall below this fraction (0.0-1.0)
}

Config controls tier resolution, limits, cleanup, and event handling.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns config with sensible defaults. consumers should override KeyExtractor and TierResolver.

type ErrorResponse

type ErrorResponse struct {
	Error      string `json:"error"`
	Message    string `json:"message"`
	Limit      int    `json:"limit"`
	Remaining  int    `json:"remaining"`
	ResetAt    int64  `json:"reset_at"`
	RetryAfter int    `json:"retry_after"`
}

ErrorResponse is returned when a request exceeds its rate limit.

type Event

type Event struct {
	Key       string
	KeyType   string // "session", "apikey", "ip"
	Tier      Tier
	Path      string
	Method    string
	Timestamp time.Time

	// rate limit state
	Allowed   bool
	Remaining int
	Limit     int
	ResetAt   time.Time

	// request context for custom handlers
	RemoteAddr string
	UserAgent  string
}

Event captures the request and limiter state for a rate-limit decision.

func NewEvent

func NewEvent(r *http.Request, key, keyType string, tier Tier, allowed bool, remaining, limit int, resetAt time.Time) Event

NewEvent builds an Event from the request and limiter state.

type EventHandler

type EventHandler interface {
	OnLimited(event Event)     // called when request is rate limited (before 429 sent)
	OnApproaching(event Event) // called when usage crosses warning threshold
	OnBlocked(event Event)     // called for escalating blocks (future feature)
}

EventHandler receives notifications on rate limit events. implementations can log, send emails, update databases, etc.

type KeyExtractor

type KeyExtractor func(r *http.Request) (key string, keyType string, err error)

KeyExtractor returns the rate limit key, key type (e.g. "session", "apikey", "ip"), and error

type Limiter

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

Limiter implements token bucket rate limiting with tier support

func New

func New(config Config) *Limiter

New creates a limiter from config.

func (*Limiter) Allow

func (l *Limiter) Allow(r *http.Request) (bool, Event)

Allow consumes a token for r and returns the decision plus event details.

func (*Limiter) Middleware

func (l *Limiter) Middleware(next http.Handler) http.Handler

Middleware wraps an http.Handler to enforce rate limits. It sets standard rate-limit headers on all responses and returns 429 with a JSON body when exceeded.

func (*Limiter) StartCleanup

func (l *Limiter) StartCleanup(ctx context.Context)

StartCleanup starts a background goroutine to remove stale visitors.

func (*Limiter) VisitorCount

func (l *Limiter) VisitorCount() int

VisitorCount returns the number of tracked visitor keys.

type NoopEventHandler

type NoopEventHandler struct{}

NoopEventHandler ignores all rate-limit events.

func (*NoopEventHandler) OnApproaching

func (n *NoopEventHandler) OnApproaching(event Event)

OnApproaching ignores an approaching-limit event.

func (*NoopEventHandler) OnBlocked

func (n *NoopEventHandler) OnBlocked(event Event)

OnBlocked ignores a blocked request event.

func (*NoopEventHandler) OnLimited

func (n *NoopEventHandler) OnLimited(event Event)

OnLimited ignores a limited request event.

type Tier

type Tier string

Tier names a rate-limit tier.

const (
	// TierUnauth is the default tier for unauthenticated requests.
	TierUnauth Tier = "unauth"
	// TierAuth is the default tier for authenticated requests.
	TierAuth Tier = "auth"
	// TierPaid is the default tier for paid accounts.
	TierPaid Tier = "paid"
)

type TierConfig

type TierConfig struct {
	Rate  rate.Limit // tokens per second
	Burst int        // max burst size
}

TierConfig defines the token bucket settings for a tier.

type TierResolver

type TierResolver func(key string, keyType string) Tier

TierResolver maps a key to its tier based on key type

Jump to

Keyboard shortcuts

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