middleware

package
v1.8.0 Latest Latest
Warning

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

Go to latest
Published: Nov 9, 2025 License: MIT Imports: 16 Imported by: 0

Documentation

Overview

Package middleware provides HTTP middleware for the API server.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func APIRateLimit added in v1.7.0

func APIRateLimit() func(http.Handler) http.Handler

APIRateLimit returns a rate limiter configured for general API endpoints. Default: 60 requests per minute per IP for standard API operations.

func CSRFProtection added in v1.7.0

func CSRFProtection() func(http.Handler) http.Handler

CSRFProtection creates a middleware that protects against Cross-Site Request Forgery (CSRF) attacks. It validates the Origin and Referer headers for state-changing requests (POST, PUT, DELETE, PATCH).

The middleware checks: 1. Origin header matches allowed origins (preferred, per Fetch Standard) 2. Referer header matches allowed origins (fallback for older browsers) 3. Allows same-origin requests by default

Configuration via environment variable:

Example usage:

r.Use(middleware.CSRFProtection())

func Metrics added in v1.7.0

func Metrics() func(http.Handler) http.Handler

Metrics creates a middleware that records Prometheus metrics for HTTP requests. It tracks request duration, in-flight requests, request/response sizes, and status codes.

func RateLimit added in v1.7.0

func RateLimit(cfg RateLimitConfig) func(http.Handler) http.Handler

RateLimit creates a rate limiting middleware using the httprate library. It uses a sliding window counter algorithm for accurate rate limiting.

Example usage:

// Limit to 10 requests per minute per IP
r.Use(middleware.RateLimit(middleware.RateLimitConfig{
    RequestLimit: 10,
    WindowSize:   time.Minute,
}))

func RefreshRateLimit added in v1.7.0

func RefreshRateLimit() func(http.Handler) http.Handler

RefreshRateLimit returns a rate limiter configured for expensive refresh operations. Default: 10 requests per minute per IP to prevent abuse of expensive operations.

func Tracing

func Tracing(tracerName string) func(http.Handler) http.Handler

Tracing creates a middleware that adds OpenTelemetry tracing to HTTP requests.

Types

type RateLimitConfig added in v1.7.0

type RateLimitConfig struct {
	// RequestLimit is the maximum number of requests allowed in the window
	RequestLimit int
	// WindowSize is the time window for rate limiting
	WindowSize time.Duration
	// KeyFunc extracts the rate limit key from the request (e.g., IP address)
	// If nil, defaults to IP-based rate limiting
	KeyFunc func(r *http.Request) (string, error)
}

RateLimitConfig holds configuration for rate limiting middleware.

Jump to

Keyboard shortcuts

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