ratelimit

package
v0.3.7 Latest Latest
Warning

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

Go to latest
Published: Jun 2, 2026 License: MIT Imports: 9 Imported by: 0

Documentation

Overview

Package ratelimit implements an in-memory per-IP, per-route-group token-bucket limiter that the API and Web UI mount as middleware.

Per the issue scope, the limiter is single-node by design — operators running multiple replicas should rate-limit at the load balancer instead. The map is bounded by an LRU per shard so a flood cannot blow up the server's memory.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func MaskIP

func MaskIP(raw string) string

MaskIP collapses an IP to its rate-limit-friendly prefix so audit entries don't explode under a sustained attack. /24 for IPv4, /64 for IPv6.

func WriteRetryAfter

func WriteRetryAfter(w http.ResponseWriter, retryAfter time.Duration)

WriteRetryAfter writes the standard 429 response (Retry-After header and a tiny body) so callers don't repeat the boilerplate.

Types

type Config

type Config struct {
	Enabled          bool
	TrustProxyHeader bool
	Groups           map[string]GroupConfig
	// MaxEntriesPerShard caps the per-shard LRU. Default 65536.
	MaxEntriesPerShard int
	// Shards is the number of shards. Power-of-two recommended. Default 4.
	Shards int
}

Config drives the limiter.

func Default

func Default() Config

Default returns a Config that matches the defaults documented in issue #52: tight on auth + enrolment, loose on everything else.

type GroupConfig

type GroupConfig struct {
	Rate  float64 // requests per second
	Burst int     // bucket capacity
}

GroupConfig is the per-route-group rate/burst pair.

type Limiter

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

Limiter is the public API the middleware calls.

func New

func New(cfg Config) *Limiter

New builds a Limiter. Returns nil when cfg.Enabled is false so the middleware can short-circuit.

func (*Limiter) Allow

func (l *Limiter) Allow(ip, group string) (allowed bool, retryAfter time.Duration)

Allow reports whether a request from ip in route-group should be served. Returns the bucket's reservation delay so callers can set Retry-After. delay == 0 means the request was admitted.

func (*Limiter) ClientIP

func (l *Limiter) ClientIP(r *http.Request) string

ClientIP returns the effective IP for the request. When the limiter is configured to trust X-Forwarded-For, the leftmost public address wins; otherwise RemoteAddr is used.

Jump to

Keyboard shortcuts

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