ratelimit

package
v0.7.0 Latest Latest
Warning

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

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

Documentation

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)
}

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"`
}

error response structure returned when rate limit is exceeded

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
}

func NewEvent

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

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

func (*Limiter) Allow

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

func (*Limiter) Middleware

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

wraps an http.Handler to enforce rate limits. sets standard rate limit headers on all responses and returns 429 with json body when limit is exceeded.

func (*Limiter) StartCleanup

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

starts background goroutine to remove stale visitors. safe to call multiple times.

func (*Limiter) VisitorCount

func (l *Limiter) VisitorCount() int

type NoopEventHandler

type NoopEventHandler struct{}

func (*NoopEventHandler) OnApproaching

func (n *NoopEventHandler) OnApproaching(event Event)

func (*NoopEventHandler) OnBlocked

func (n *NoopEventHandler) OnBlocked(event Event)

func (*NoopEventHandler) OnLimited

func (n *NoopEventHandler) OnLimited(event Event)

type Tier

type Tier string
const (
	TierUnauth Tier = "unauth"
	TierAuth   Tier = "auth"
	TierPaid   Tier = "paid"
)

type TierConfig

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

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