middleware

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Mar 27, 2026 License: Apache-2.0 Imports: 28 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CORS

func CORS(allowedOrigins []string) func(http.Handler) http.Handler

CORS adds permissive CORS policy for configured origins.

func Chain

func Chain(middlewares ...func(http.Handler) http.Handler) func(http.Handler) http.Handler

Chain combines middleware in declaration order.

func ChainStreamInterceptors

func ChainStreamInterceptors(interceptors ...grpc.StreamServerInterceptor) grpc.StreamServerInterceptor

ChainStreamInterceptors combines stream interceptors in declaration order.

func ChainUnaryInterceptors

func ChainUnaryInterceptors(interceptors ...grpc.UnaryServerInterceptor) grpc.UnaryServerInterceptor

ChainUnaryInterceptors combines unary interceptors in declaration order.

func CircuitBreaker

func CircuitBreaker(cfg CircuitBreakerConfig) func(http.Handler) http.Handler

CircuitBreaker returns HTTP middleware that wraps requests in a circuit breaker. Returns 503 Service Unavailable when the circuit is open. Counts 5xx responses as failures.

func ContentType

func ContentType(contentType string) func(http.Handler) http.Handler

ContentType sets default content type for API endpoints.

func GRPCCircuitBreakerStream

func GRPCCircuitBreakerStream(cfg CircuitBreakerConfig) grpc.StreamServerInterceptor

GRPCCircuitBreakerStream wraps stream requests in a circuit breaker.

func GRPCCircuitBreakerUnary

func GRPCCircuitBreakerUnary(cfg CircuitBreakerConfig) grpc.UnaryServerInterceptor

GRPCCircuitBreakerUnary wraps unary requests in a circuit breaker.

func GRPCLoggingStream

func GRPCLoggingStream() grpc.StreamServerInterceptor

GRPCLoggingStream records stream request metadata via slog.

func GRPCLoggingUnary

func GRPCLoggingUnary() grpc.UnaryServerInterceptor

GRPCLoggingUnary records unary request metadata via slog.

func GRPCMetricsStream

func GRPCMetricsStream(metrics *telemetry.GRPCMetrics) grpc.StreamServerInterceptor

GRPCMetricsStream records shared gRPC metrics for stream calls.

func GRPCMetricsUnary

func GRPCMetricsUnary(metrics *telemetry.GRPCMetrics) grpc.UnaryServerInterceptor

GRPCMetricsUnary records shared gRPC metrics for unary calls.

func GRPCRateLimitStream

func GRPCRateLimitStream(limiter RateLimiterInterface) grpc.StreamServerInterceptor

GRPCRateLimitStream rate-limits streaming requests.

func GRPCRateLimitStreamWithKey

func GRPCRateLimitStreamWithKey(limiter KeyedRateLimiter, extractor StreamRateLimitKeyExtractor) grpc.StreamServerInterceptor

GRPCRateLimitStreamWithKey applies keyed stream rate limiting.

func GRPCRateLimitUnary

func GRPCRateLimitUnary(limiter RateLimiterInterface) grpc.UnaryServerInterceptor

GRPCRateLimitUnary rate-limits unary requests.

func GRPCRateLimitUnaryWithKey

func GRPCRateLimitUnaryWithKey(limiter KeyedRateLimiter, extractor UnaryRateLimitKeyExtractor) grpc.UnaryServerInterceptor

GRPCRateLimitUnaryWithKey applies keyed unary rate limiting.

func GRPCRecoveryStream

func GRPCRecoveryStream() grpc.StreamServerInterceptor

GRPCRecoveryStream prevents panics from crashing the process.

func GRPCRecoveryUnary

func GRPCRecoveryUnary() grpc.UnaryServerInterceptor

GRPCRecoveryUnary prevents panics from crashing the process.

func GRPCRequestIDStream

func GRPCRequestIDStream() grpc.StreamServerInterceptor

GRPCRequestIDStream injects request IDs into stream contexts and headers.

func GRPCRequestIDUnary

func GRPCRequestIDUnary() grpc.UnaryServerInterceptor

GRPCRequestIDUnary injects request IDs into unary contexts and headers.

func GRPCTracingStream

func GRPCTracingStream(tracerName string) grpc.StreamServerInterceptor

GRPCTracingStream creates an OpenTelemetry span for stream requests. Callers are responsible for configuring the global text map propagator before using tracing middleware, for example via InitOTelPropagator.

func GRPCTracingUnary

func GRPCTracingUnary(tracerName string) grpc.UnaryServerInterceptor

GRPCTracingUnary creates an OpenTelemetry span for unary requests. Callers are responsible for configuring the global text map propagator before using tracing middleware, for example via InitOTelPropagator.

func GetRequestID

func GetRequestID(ctx context.Context) string

GetRequestID returns request ID from context.

func GetSpanID

func GetSpanID(ctx context.Context) string

GetSpanID extracts the span ID from the OTel span context.

func GetTraceID

func GetTraceID(ctx context.Context) string

GetTraceID extracts the trace ID from the OTel span context. Falls back to request ID if no active span.

func InitOTelPropagator

func InitOTelPropagator()

InitOTelPropagator sets up the global W3C TraceContext propagator. Applications should call this during startup before using tracing middleware.

func Logging

func Logging() func(http.Handler) http.Handler

Logging records request metadata via slog.

func MaxBodySize

func MaxBodySize(maxBytes int64) func(http.Handler) http.Handler

MaxBodySize rejects oversized request bodies early.

func OTelHTTPMiddleware

func OTelHTTPMiddleware(serviceName string) func(http.Handler) http.Handler

OTelHTTPMiddleware returns HTTP middleware with OpenTelemetry instrumentation.

func RateLimit

func RateLimit(limiter *RateLimiter) func(http.Handler) http.Handler

RateLimit creates rate limiting middleware.

func RateLimitWithInterface

func RateLimitWithInterface(limiter RateLimiterInterface) func(http.Handler) http.Handler

RateLimitWithInterface creates rate limiting middleware with any RateLimiterInterface.

func RateLimitWithKey

func RateLimitWithKey(limiter KeyedRateLimiter, extractor RateLimitKeyExtractor) func(http.Handler) http.Handler

RateLimitWithKey creates keyed rate limiting middleware.

func Recovery

func Recovery() func(http.Handler) http.Handler

Recovery catches panics and prevents process crashes.

func RequestID

func RequestID() func(http.Handler) http.Handler

RequestID ensures every request has a stable request identifier.

func RequestTimeout

func RequestTimeout(timeout time.Duration) func(http.Handler) http.Handler

RequestTimeout attaches a timeout to each request context.

func Tracing

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

Tracing creates OpenTelemetry-compatible tracing middleware. Extracts incoming trace context from W3C headers, creates a new span per request, and injects trace context into response headers.

Types

type CircuitBreakerConfig

type CircuitBreakerConfig struct {
	Name        string
	MaxRequests uint32        // max requests allowed in half-open state
	Interval    time.Duration // cyclic period of closed state to clear counts
	Timeout     time.Duration // period of open state before moving to half-open
	ReadyToTrip uint32        // consecutive failures before opening circuit
}

CircuitBreakerConfig holds configuration for the circuit breaker middleware.

func DefaultCircuitBreakerConfig

func DefaultCircuitBreakerConfig() CircuitBreakerConfig

DefaultCircuitBreakerConfig returns sensible defaults.

type KeyedRateLimiter

type KeyedRateLimiter interface {
	AllowKey(key string) bool
}

KeyedRateLimiter defines keyed rate limiting for per-client or per-tenant flows.

func NewRedisOrPartitionedRateLimiter

func NewRedisOrPartitionedRateLimiter(cfg RedisRateLimiterConfig, entryTTL time.Duration) (KeyedRateLimiter, io.Closer, error)

NewRedisOrPartitionedRateLimiter returns a Redis-backed keyed limiter when available and falls back to a partitioned in-memory keyed limiter during bootstrap failures.

type PartitionedRateLimiter

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

PartitionedRateLimiter provides per-key in-memory rate limiting with TTL cleanup.

func NewPartitionedRateLimiter

func NewPartitionedRateLimiter(requestsPerSecond int, burst int, entryTTL time.Duration) *PartitionedRateLimiter

NewPartitionedRateLimiter creates a keyed in-memory rate limiter.

func (*PartitionedRateLimiter) AllowKey

func (rl *PartitionedRateLimiter) AllowKey(key string) bool

AllowKey checks the per-key bucket and lazily evicts stale buckets.

type RateLimitKeyExtractor

type RateLimitKeyExtractor func(*http.Request) string

RateLimitKeyExtractor returns the logical rate-limit key for an HTTP request.

type RateLimiter

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

RateLimiter implements token bucket rate limiting.

func NewRateLimiter

func NewRateLimiter(requestsPerSecond int, burst int) *RateLimiter

NewRateLimiter creates a new rate limiter.

func (*RateLimiter) Allow

func (rl *RateLimiter) Allow() bool

Allow checks if a request is allowed.

func (*RateLimiter) AllowKey

func (rl *RateLimiter) AllowKey(_ string) bool

AllowKey satisfies KeyedRateLimiter using the shared in-memory bucket.

type RateLimiterInterface

type RateLimiterInterface interface {
	Allow() bool
}

RateLimiterInterface defines the contract for rate limiters. Both in-memory and Redis implementations satisfy this interface.

type RedisRateLimiter

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

RedisRateLimiter provides distributed token bucket rate limiting. Falls back to in-memory limiting if Redis is unavailable (Circuit Breaker pattern).

func NewRedisRateLimiter

func NewRedisRateLimiter(cfg RedisRateLimiterConfig) (*RedisRateLimiter, error)

NewRedisRateLimiter creates a new distributed rate limiter. Returns an error if Redis connection fails (caller should fall back to in-memory).

func (*RedisRateLimiter) Allow

func (rl *RedisRateLimiter) Allow() bool

Allow checks if a request is allowed using the token bucket algorithm. Uses the default global key for rate limiting. Satisfies RateLimiterInterface.

func (*RedisRateLimiter) AllowKey

func (rl *RedisRateLimiter) AllowKey(key string) bool

AllowKey checks if a request is allowed for a specific key (IP, API key, etc.).

func (*RedisRateLimiter) Close

func (rl *RedisRateLimiter) Close() error

Close closes the Redis connection.

func (*RedisRateLimiter) HealthCheck

func (rl *RedisRateLimiter) HealthCheck(ctx context.Context) error

HealthCheck verifies Redis connectivity.

type RedisRateLimiterConfig

type RedisRateLimiterConfig struct {
	RedisURL      string
	RedisPassword string
	RedisDB       int
	RedisTLS      bool

	RequestsPerSecond int
	Burst             int
	KeyTTL            time.Duration // Default: 1h

	// Circuit breaker settings
	FailureThreshold int           // Default: 3
	ResetTimeout     time.Duration // Default: 30s
}

RedisRateLimiterConfig holds configuration for the Redis rate limiter.

type StreamRateLimitKeyExtractor

type StreamRateLimitKeyExtractor func(any, grpc.ServerStream, *grpc.StreamServerInfo) string

StreamRateLimitKeyExtractor returns the rate-limit key for a streaming gRPC request.

type UnaryRateLimitKeyExtractor

type UnaryRateLimitKeyExtractor func(context.Context, any, *grpc.UnaryServerInfo) string

UnaryRateLimitKeyExtractor returns the rate-limit key for a unary gRPC request.

Jump to

Keyboard shortcuts

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