middleware

package
v1.3.0 Latest Latest
Warning

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

Go to latest
Published: May 29, 2026 License: MIT Imports: 12 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const RequestIDHeader = "X-Request-ID"

Variables

View Source
var (
	ErrMissingAuthHeader = errors.New("missing authorization header")
	ErrInvalidAuthFormat = errors.New("invalid authorization format")
	ErrInvalidAPIKey     = errors.New("invalid api key")
)

Authentication errors (sentinel errors)

Functions

func ExtractIPWithForwardedFor

func ExtractIPWithForwardedFor(r *http.Request) string

ExtractIPWithForwardedFor returns an IP extractor that checks X-Forwarded-For and X-Real-IP headers. Use this when the API is behind a proxy/load balancer.

WARNING: Only use this if your proxy is configured to set these headers correctly. If misconfigured, clients can spoof their IP addresses to bypass rate limits.

Priority order: 1. X-Forwarded-For (leftmost IP = original client) 2. X-Real-IP 3. RemoteAddr (fallback)

func GetRequestID

func GetRequestID(ctx context.Context) string

Types

type APIKeyAuthOption

type APIKeyAuthOption func(*apiKeyAuthConfig)

APIKeyAuthOption is a functional option for configuring APIKeyAuth middleware

func WithAuthErrorHandler

func WithAuthErrorHandler(handler func(w http.ResponseWriter, r *http.Request, err error)) APIKeyAuthOption

WithAuthErrorHandler sets the error handler callback The handler is called when authentication fails and should write the HTTP response

func WithTokenExtractor

func WithTokenExtractor(extractor func(authHeader string) (string, bool)) APIKeyAuthOption

WithTokenExtractor sets a custom token extraction function Defaults to Bearer token extraction if not provided

type Chain

type Chain []Middleware

func (Chain) Then

func (c Chain) Then(h http.Handler) http.Handler

func (Chain) ThenFunc

func (c Chain) ThenFunc(h http.HandlerFunc) http.Handler

type Middleware

type Middleware func(http.Handler) http.Handler

func APIKeyAuth

func APIKeyAuth(validKey string, opts ...APIKeyAuthOption) Middleware

APIKeyAuth creates a middleware that validates bearer tokens The validKey parameter is required; use options for additional configuration

func Logging

func Logging(logger *slog.Logger) Middleware

func MaxBodySize

func MaxBodySize(maxBytes int64) Middleware

MaxBodySize returns middleware that limits request body size. If the request body exceeds maxBytes, subsequent reads will fail and handlers should return a 413 error.

This middleware wraps the request body with http.MaxBytesReader, which enforces the size limit when the body is actually read.

func RateLimit

func RateLimit(limiter *ratelimit.Limiter, opts ...RateLimitOption) Middleware

RateLimit creates middleware that enforces per-IP rate limiting using the provided rate limiter. The limiter's lifecycle (creation and cleanup) is managed by the caller.

Example:

limiter := ratelimit.NewLimiter(1000)
defer limiter.Stop()

mw := middleware.RateLimit(
    limiter,
    middleware.WithIPExtractor(middleware.ExtractIPWithForwardedFor),
    middleware.WithRateLimitErrorHandler(customHandler),
)

The middleware: - Extracts a key (typically IP address) from each request - Checks if the key is allowed by the rate limiter - Returns 429 Too Many Requests with Retry-After header when limit exceeded

func RequestID

func RequestID() Middleware

type RateLimitOption

type RateLimitOption func(*rateLimitConfig)

RateLimitOption is a functional option for configuring RateLimit middleware

func WithIPExtractor

func WithIPExtractor(extractor func(r *http.Request) string) RateLimitOption

WithIPExtractor sets a custom IP extraction function. Default: uses r.RemoteAddr

func WithRateLimitErrorHandler

func WithRateLimitErrorHandler(handler func(w http.ResponseWriter, r *http.Request)) RateLimitOption

WithRateLimitErrorHandler sets the error handler callback. The handler is called when rate limit is exceeded and should write the HTTP response.

Jump to

Keyboard shortcuts

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