Documentation
¶
Overview ¶
Package middleware provides HTTP middleware for the API server.
Index ¶
- func APIRateLimit() func(http.Handler) http.Handler
- func CSRFProtection() func(http.Handler) http.Handler
- func Metrics() func(http.Handler) http.Handler
- func RateLimit(cfg RateLimitConfig) func(http.Handler) http.Handler
- func RefreshRateLimit() func(http.Handler) http.Handler
- func Tracing(tracerName string) func(http.Handler) http.Handler
- type RateLimitConfig
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func APIRateLimit ¶ added in v1.7.0
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
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:
- XG2G_ALLOWED_ORIGINS: Comma-separated list of allowed origins (e.g., "http://localhost:8080,https://example.com")
- If not set, only same-origin requests are allowed
Example usage:
r.Use(middleware.CSRFProtection())
func Metrics ¶ added in v1.7.0
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
RefreshRateLimit returns a rate limiter configured for expensive refresh operations. Default: 10 requests per minute per IP to prevent abuse of expensive operations.
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.