middleware

package
v1.0.78 Latest Latest
Warning

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

Go to latest
Published: Dec 15, 2025 License: Apache-2.0 Imports: 40 Imported by: 0

Documentation

Overview

Package middleware contains production‑ready middleware for Lift applications, including request correlation, structured logging, panic recovery, error formatting, input validation, JWT authentication, rate limiting, idempotency, retries, circuit breaking, load shedding, security headers, and service mesh helpers. Middleware composes via the Lift Middleware type:

app.Use(middleware.RequestID())
app.Use(middleware.Logger())
app.Use(middleware.Recover())
app.Use(middleware.ErrorHandler())
app.Use(middleware.JWTAuth(jwtConfig))

Middleware is evaluated in registration order (last added runs closest to the handler). Functions here are safe defaults for serverless workloads.

Index

Examples

Constants

View Source
const (
	LoadSheddingRandom   LoadSheddingStrategy = "random"   // Random shedding based on probability
	LoadSheddingPriority LoadSheddingStrategy = "priority" // Priority-based shedding
	LoadSheddingAdaptive LoadSheddingStrategy = "adaptive" // Adaptive shedding based on system metrics
	LoadSheddingCircuit  LoadSheddingStrategy = "circuit"  // Circuit breaker style shedding
	LoadSheddingCustom   LoadSheddingStrategy = "custom"   // Custom shedding algorithm

	// Backward compatibility aliases
	LoadSheddingStrategyRandom   = LoadSheddingRandom
	LoadSheddingStrategyPriority = LoadSheddingPriority
	LoadSheddingStrategyAdaptive = LoadSheddingAdaptive
	LoadSheddingStrategyCircuit  = LoadSheddingCircuit
	LoadSheddingStrategyCustom   = LoadSheddingCustom
)

Variables

This section is empty.

Functions

func APISecurityHeaders

func APISecurityHeaders() lift.Middleware

APISecurityHeaders returns security headers optimized for API endpoints

func AdaptiveRateLimitMiddleware

func AdaptiveRateLimitMiddleware(config RateLimitConfig) lift.Middleware

AdaptiveRateLimitMiddleware creates an adaptive rate limiting middleware

func AdaptiveTimeoutCalculator

func AdaptiveTimeoutCalculator(baseTimeout time.Duration) func(*lift.Context) time.Duration

AdaptiveTimeoutCalculator creates a timeout calculator that adapts based on request complexity

func BulkheadMiddleware

func BulkheadMiddleware(config BulkheadConfig) lift.Middleware

BulkheadMiddleware creates a bulkhead pattern middleware

func BurstRateLimitMiddleware

func BurstRateLimitMiddleware(config RateLimitConfig) lift.Middleware

BurstRateLimitMiddleware creates a burst-aware rate limiting middleware

func CircuitBreakerMiddleware

func CircuitBreakerMiddleware(config CircuitBreakerConfig) lift.Middleware

CircuitBreakerMiddleware creates a circuit breaker middleware

func CleanupExpiredEntries

func CleanupExpiredEntries(_ context.Context, _ RateLimitConfig) error

CleanupExpiredEntries removes expired rate limit entries

func CompositeRateLimit

func CompositeRateLimit(config RateLimitConfig) lift.Middleware

CompositeRateLimit creates a composite rate limiting middleware with multiple strategies

func EndpointRateLimit

func EndpointRateLimit(limit int, window time.Duration) lift.Middleware

EndpointRateLimit creates an endpoint-specific rate limiting middleware

func EnhancedObservabilityMiddleware

func EnhancedObservabilityMiddleware(config EnhancedObservabilityConfig) lift.Middleware

EnhancedObservabilityMiddleware provides comprehensive observability with logging, metrics, and tracing

func FeatureFlagMiddleware added in v1.0.37

func FeatureFlagMiddleware(ff *features.FeatureFlags) lift.Middleware

FeatureFlagMiddleware injects feature flags into the request context

func GetFeatureFlags added in v1.0.37

func GetFeatureFlags(ctx *lift.Context) *features.FeatureFlags

GetFeatureFlags retrieves the feature flags from context

func HealthCheckMiddleware

func HealthCheckMiddleware(config HealthCheckConfig) lift.Middleware

HealthCheckMiddleware creates a health check middleware

func HealthCheckObservability

func HealthCheckObservability(config EnhancedObservabilityConfig) func() error

HealthCheckObservability creates a health check for the observability stack

func HealthMiddleware

func HealthMiddleware(config HealthConfig) lift.Middleware

HealthMiddleware is an alias for HealthCheckMiddleware for backward compatibility

func IPRateLimit

func IPRateLimit(limit int, window time.Duration) lift.Middleware

IPRateLimit creates an IP-based rate limiting middleware

func IPRateLimitWithLimited added in v1.0.35

func IPRateLimitWithLimited(limit int, window time.Duration) (lift.Middleware, error)

IPRateLimitWithLimited creates an IP-based rate limiter

func InputValidation

func InputValidation(config ValidationConfig) lift.Middleware

InputValidation creates comprehensive input validation middleware

Example

Example of input validation middleware using the default secure config.

package main

import (
	"github.com/pay-theory/lift/pkg/lift"
	"github.com/pay-theory/lift/pkg/middleware"
)

func main() {
	app := lift.New()

	// Apply comprehensive request validation (headers, content-type, sizes, path/query params, basic XSS/SQLi checks).
	app.Use(middleware.InputValidation(middleware.DefaultValidationConfig()))

	_ = app.POST("/submit", func(ctx *lift.Context) error {
		// If we got here, request passed validation.
		return ctx.Text("ok")
	})
}

func IsFeatureEnabled added in v1.0.37

func IsFeatureEnabled(ctx *lift.Context, flag string) bool

IsFeatureEnabled checks if a feature is enabled from context

func JWT

func JWT(config security.JWTConfig) lift.Middleware

JWT creates JWT authentication middleware

func JWTAuth

func JWTAuth(config JWTConfig) lift.Middleware

JWTAuth creates a JWT authentication middleware

Example

Example demonstrating JWT authentication configuration.

package main

import (
	"github.com/pay-theory/lift/pkg/lift"
	"github.com/pay-theory/lift/pkg/middleware"
)

func main() {
	app := lift.New()

	// Protect all routes under /api with JWT
	api := app.Group("/api")
	api.Use(middleware.JWTAuth(middleware.JWTConfig{
		Secret:      "test-secret",
		Algorithm:   "HS256",
		TokenLookup: "header:Authorization",
		SkipPaths:   []string{"/api/public"},
	}))

	// Register protected routes under /api
	_ = api.GET("/profile", func(ctx *lift.Context) error { return ctx.Text("ok") })
}

func JWTOptional

func JWTOptional(config security.JWTConfig) lift.Middleware

JWTOptional creates optional JWT authentication middleware If no token is provided, continues with anonymous principal

func LimitedRateLimit added in v1.0.35

func LimitedRateLimit(config LimitedConfig) (lift.Middleware, error)

LimitedRateLimit creates a rate limiting middleware using the limited library This is the CORRECT way to do rate limiting with DynamoDB in Lift

func LoadBasedTimeoutCalculator

func LoadBasedTimeoutCalculator(baseTimeout time.Duration, loadMetrics *LoadMetrics) func(*lift.Context) time.Duration

LoadBasedTimeoutCalculator creates a timeout calculator that adjusts based on system load

func LoadSheddingMiddleware

func LoadSheddingMiddleware(config LoadSheddingConfig) lift.Middleware

LoadSheddingMiddleware creates a load shedding middleware

func MetricsOnlyMiddleware

func MetricsOnlyMiddleware(metrics lift.MetricsCollector) lift.Middleware

MetricsOnlyMiddleware provides lightweight metrics collection without logging

func ObservabilityMiddleware

func ObservabilityMiddleware(config ObservabilityConfig) lift.Middleware

ObservabilityMiddleware provides comprehensive logging and metrics collection

func PriorityTimeoutCalculator

func PriorityTimeoutCalculator(baseTimeout time.Duration) func(*lift.Context) time.Duration

PriorityTimeoutCalculator creates a timeout calculator based on request priority

func PropagateTraceHeaders added in v1.0.37

func PropagateTraceHeaders() lift.Middleware

PropagateTraceHeaders is a helper middleware that propagates trace headers to outgoing requests

func RateLimit

func RateLimit(config RateLimitConfig) lift.Middleware

RateLimit creates a rate limiting middleware with the given configuration

func RateLimitMiddleware

func RateLimitMiddleware(config RateLimitConfig) lift.Middleware

RateLimitMiddleware creates a rate limiting middleware with DynamORM backend

func RequireRole

func RequireRole(roles ...string) lift.Middleware

RequireRole creates middleware that requires specific roles

func RequireScope

func RequireScope(scopes ...string) lift.Middleware

RequireScope creates middleware that requires specific scopes

func RequireTenant

func RequireTenant(tenantID string) lift.Middleware

RequireTenant creates middleware that validates tenant access

func RetryMiddleware

func RetryMiddleware(config RetryConfig) lift.Middleware

RetryMiddleware creates a retry middleware

func SecurityAuditHeaders

func SecurityAuditHeaders() lift.Middleware

SecurityAuditHeaders returns middleware that adds headers for security auditing

func SecurityHeaders

func SecurityHeaders(config SecurityHeadersConfig) lift.Middleware

SecurityHeaders returns the security headers middleware

func SecurityHeadersWithNonce

func SecurityHeadersWithNonce() lift.Middleware

SecurityHeadersWithNonce creates security headers with a nonce for CSP

func ServiceMesh added in v1.0.37

func ServiceMesh(config ServiceMeshConfig) (lift.Middleware, error)

ServiceMesh creates a service mesh middleware with the given configuration

func SlidingWindowRateLimit added in v1.0.37

func SlidingWindowRateLimit(_ int, _ time.Duration) (lift.Middleware, error)

SlidingWindowRateLimit creates a sliding window rate limiter

func StrictSecurityHeaders

func StrictSecurityHeaders() lift.Middleware

StrictSecurityHeaders returns a middleware with very strict security settings

func TenantRateLimit

func TenantRateLimit(limit int, window time.Duration) lift.Middleware

TenantRateLimit creates a tenant-specific rate limiting middleware

func TenantRateLimitWithLimited added in v1.0.35

func TenantRateLimitWithLimited(limit int, window time.Duration) (lift.Middleware, error)

TenantRateLimitWithLimited creates a tenant-based rate limiter

func TimeoutMiddleware

func TimeoutMiddleware(config TimeoutConfig) lift.Middleware

TimeoutMiddleware creates a timeout middleware

func UpdateRateLimitStats

func UpdateRateLimitStats(ctx context.Context, config RateLimitConfig, allowed bool, hasError bool) error

UpdateRateLimitStats updates aggregate statistics (called by rate limiter)

func UserRateLimit

func UserRateLimit(limit int, window time.Duration) lift.Middleware

UserRateLimit creates a user-specific rate limiting middleware

func UserRateLimitWithLimited added in v1.0.35

func UserRateLimitWithLimited(limit int, window time.Duration) (lift.Middleware, error)

UserRateLimitWithLimited creates a user-based rate limiter

Example

Example demonstrating rate limiting with the Limited-backed middleware.

package main

import (
	"time"

	"github.com/pay-theory/lift/pkg/lift"
	"github.com/pay-theory/lift/pkg/middleware"
)

func main() {
	app := lift.New()

	// Create limiter. In production, ensure AWS_REGION is set.
	limiter, _ := middleware.UserRateLimitWithLimited(100, 15*time.Minute)
	if limiter != nil {
		app.Use(limiter)
	}

	_ = app.GET("/data", func(ctx *lift.Context) error { return ctx.Text("ok") })
}

func ValidateAlphaNumeric

func ValidateAlphaNumeric(value string) error

ValidateAlphaNumeric validates that a string contains only alphanumeric characters

func ValidateEmail

func ValidateEmail(email string) error

ValidateEmail validates email format

func ValidateLength

func ValidateLength(minLen, maxLen int) func(string) error

ValidateLength validates string length

func ValidateNumeric

func ValidateNumeric(value string) error

ValidateNumeric validates that a string contains only numeric characters

func ValidateUUID

func ValidateUUID(uuid string) error

ValidateUUID validates UUID format

func WebSocketAuth

func WebSocketAuth(config WebSocketAuthConfig) lift.Middleware

WebSocketAuth creates authentication middleware for WebSocket connections

func WebSocketAuthFromHeader

func WebSocketAuthFromHeader(headerName string) func(ctx *lift.Context) string

WebSocketAuthFromHeader is a token extractor that gets the token from headers

func WebSocketAuthFromQuery

func WebSocketAuthFromQuery(paramName string) func(ctx *lift.Context) string

WebSocketAuthFromQuery is a simple token extractor that gets the token from query parameters

func WebSocketConnectionMetrics

func WebSocketConnectionMetrics(metrics lift.MetricsCollector, store lift.ConnectionStore) lift.Middleware

WebSocketConnectionMetrics creates middleware that tracks connection lifecycle

func WebSocketMetrics

func WebSocketMetrics(metrics lift.MetricsCollector) lift.Middleware

WebSocketMetrics creates metrics middleware for WebSocket operations

func WithJWTAuth

func WithJWTAuth(secret string) lift.Middleware

WithJWTAuth is a convenience function for creating JWT middleware with minimal config

Types

type BulkheadConfig

type BulkheadConfig struct {
	Logger                   observability.StructuredLogger    `json:"-"`
	Metrics                  observability.MetricsCollector    `json:"-"`
	PerTenantLimits          map[string]int                    `json:"per_tenant_limits"`
	PerOperationLimits       map[string]int                    `json:"per_operation_limits"`
	PriorityExtractor        func(*lift.Context) int           `json:"-"`
	RejectionHandler         func(*lift.Context, string) error `json:"-"`
	Name                     string                            `json:"name"`
	MaxWaitTime              time.Duration                     `json:"max_wait_time"`
	DefaultTenantLimit       int                               `json:"default_tenant_limit"`
	MaxConcurrentRequests    int                               `json:"max_concurrent_requests"`
	DefaultOperationLimit    int                               `json:"default_operation_limit"`
	HighPriorityThreshold    int                               `json:"high_priority_threshold"`
	EnableTenantIsolation    bool                              `json:"enable_tenant_isolation"`
	EnablePriority           bool                              `json:"enable_priority"`
	EnableMetrics            bool                              `json:"enable_metrics"`
	EnableOperationIsolation bool                              `json:"enable_operation_isolation"`
}

BulkheadConfig holds configuration for the bulkhead pattern

func NewBasicBulkhead

func NewBasicBulkhead(name string, maxConcurrent int) BulkheadConfig

NewBasicBulkhead creates a basic bulkhead with sensible defaults

func NewOperationBulkhead

func NewOperationBulkhead(name string, maxConcurrent int, operationLimits map[string]int) BulkheadConfig

NewOperationBulkhead creates an operation-isolated bulkhead

func NewPriorityBulkhead

func NewPriorityBulkhead(name string, maxConcurrent int, priorityExtractor func(*lift.Context) int) BulkheadConfig

NewPriorityBulkhead creates a priority-aware bulkhead

func NewTenantBulkhead

func NewTenantBulkhead(name string, maxConcurrent int, tenantLimits map[string]int) BulkheadConfig

NewTenantBulkhead creates a tenant-isolated bulkhead

type BulkheadStats

type BulkheadStats struct {
	TenantStats         map[string]*ResourceStats `json:"tenant_stats,omitempty"`
	OperationStats      map[string]*ResourceStats `json:"operation_stats,omitempty"`
	Name                string                    `json:"name"`
	ActiveRequests      int                       `json:"active_requests"`
	QueuedRequests      int                       `json:"queued_requests"`
	TotalRequests       int64                     `json:"total_requests"`
	RejectedRequests    int64                     `json:"rejected_requests"`
	CompletedRequests   int64                     `json:"completed_requests"`
	AverageWaitTime     time.Duration             `json:"average_wait_time"`
	MaxWaitTime         time.Duration             `json:"max_wait_time"`
	ResourceUtilization float64                   `json:"resource_utilization"`
}

BulkheadStats provides statistics about bulkhead performance

type CircuitBreakerConfig

type CircuitBreakerConfig struct {
	Metrics               observability.MetricsCollector                 `json:"-"`
	Logger                observability.StructuredLogger                 `json:"-"`
	ShouldTrip            func(error) bool                               `json:"-"`
	OnStateChange         func(CircuitBreakerState, CircuitBreakerState) `json:"-"`
	FallbackHandler       func(*lift.Context) error                      `json:"-"`
	Name                  string                                         `json:"name"`
	MinRequestThreshold   int                                            `json:"min_request_threshold"`
	RetryBackoff          time.Duration                                  `json:"retry_backoff"`
	MaxRetryAttempts      int                                            `json:"max_retry_attempts"`
	SlidingWindowSize     time.Duration                                  `json:"sliding_window_size"`
	FailureThreshold      int                                            `json:"failure_threshold"`
	ErrorRateThreshold    float64                                        `json:"error_rate_threshold"`
	Timeout               time.Duration                                  `json:"timeout"`
	SuccessThreshold      int                                            `json:"success_threshold"`
	PerTenant             bool                                           `json:"per_tenant"`
	PerOperation          bool                                           `json:"per_operation"`
	EnableTenantIsolation bool                                           `json:"enable_tenant_isolation"`
	EnableMetrics         bool                                           `json:"enable_metrics"`
}

CircuitBreakerConfig holds configuration for the circuit breaker

func NewAdvancedCircuitBreaker

func NewAdvancedCircuitBreaker(name string, shouldTrip func(error) bool, fallback func(*lift.Context) error) CircuitBreakerConfig

NewAdvancedCircuitBreaker creates a circuit breaker with custom failure detection

func NewBasicCircuitBreaker

func NewBasicCircuitBreaker(name string) CircuitBreakerConfig

NewBasicCircuitBreaker creates a basic circuit breaker with sensible defaults

func NewOperationCircuitBreaker

func NewOperationCircuitBreaker(name string) CircuitBreakerConfig

NewOperationCircuitBreaker creates a per-operation circuit breaker

func NewTenantCircuitBreaker

func NewTenantCircuitBreaker(name string) CircuitBreakerConfig

NewTenantCircuitBreaker creates a per-tenant circuit breaker

type CircuitBreakerState

type CircuitBreakerState string

CircuitBreakerState represents the current state of the circuit breaker

const (
	CircuitBreakerClosed   CircuitBreakerState = "closed"    // Normal operation
	CircuitBreakerOpen     CircuitBreakerState = "open"      // Failing fast
	CircuitBreakerHalfOpen CircuitBreakerState = "half_open" // Testing recovery
)

type CircuitBreakerStats

type CircuitBreakerStats struct {
	LastFailure          time.Time           `json:"last_failure"`
	LastSuccess          time.Time           `json:"last_success"`
	StateChangedAt       time.Time           `json:"state_changed_at"`
	NextRetryAt          time.Time           `json:"next_retry_at,omitempty"`
	State                CircuitBreakerState `json:"state"`
	FailureCount         int64               `json:"failure_count"`
	SuccessCount         int64               `json:"success_count"`
	TotalRequests        int64               `json:"total_requests"`
	ErrorRate            float64             `json:"error_rate"`
	ConsecutiveFailures  int                 `json:"consecutive_failures"`
	ConsecutiveSuccesses int                 `json:"consecutive_successes"`
}

CircuitBreakerStats provides statistics about circuit breaker performance

type CookieToken

type CookieToken struct {
	Name     string
	Value    string
	SameSite string
	Path     string
	Domain   string
	MaxAge   int
	HttpOnly bool
	Secure   bool
}

CookieToken represents a parsed HTTP cookie

type DatabaseHealthChecker

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

DatabaseHealthChecker checks database connectivity

func NewDatabaseHealthChecker

func NewDatabaseHealthChecker(name string, required bool, testFunc func(context.Context) error) *DatabaseHealthChecker

func (*DatabaseHealthChecker) Check

func (*DatabaseHealthChecker) IsRequired

func (d *DatabaseHealthChecker) IsRequired() bool

func (*DatabaseHealthChecker) Name

func (d *DatabaseHealthChecker) Name() string

type DynamORMIdempotencyStore added in v1.0.37

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

DynamORMIdempotencyStore implements IdempotencyStore using DynamORM

func NewDynamORMIdempotencyStore added in v1.0.37

func NewDynamORMIdempotencyStore() *DynamORMIdempotencyStore

NewDynamORMIdempotencyStore creates a new DynamORM-based idempotency store This assumes the DynamORM middleware has been configured in the Lift app

func NewDynamORMIdempotencyStoreWithWrapper added in v1.0.37

func NewDynamORMIdempotencyStoreWithWrapper(wrapper *dynamorm.DynamORMWrapper) *DynamORMIdempotencyStore

NewDynamORMIdempotencyStoreWithWrapper creates a store with a specific DynamORM wrapper

func (*DynamORMIdempotencyStore) Delete added in v1.0.37

func (d *DynamORMIdempotencyStore) Delete(ctx context.Context, key string) error

Delete removes a key from the store

func (*DynamORMIdempotencyStore) Get added in v1.0.37

Get retrieves a stored response by key

func (*DynamORMIdempotencyStore) Set added in v1.0.37

Set stores a response with the given key

func (*DynamORMIdempotencyStore) SetProcessing added in v1.0.37

func (d *DynamORMIdempotencyStore) SetProcessing(ctx context.Context, key string, expiresAt time.Time) error

SetProcessing marks a key as being processed

type EnhancedObservabilityConfig

type EnhancedObservabilityConfig struct {
	Metrics           observability.MetricsCollector
	Logger            observability.StructuredLogger
	Tracer            *xray.XRayTracer
	OperationNameFunc func(*lift.Context) string
	TenantIDFunc      func(*lift.Context) string
	UserIDFunc        func(*lift.Context) string
	DefaultTags       map[string]string `json:"default_tags"`
	Sampler           func() float64
	SampleRate        float64 `json:"sample_rate"`
	MaxBodyLogSize    int     `json:"max_body_log_size"`
	EnableLogging     bool    `json:"enable_logging"`
	LogResponseBody   bool    `json:"log_response_body"`
	LogRequestBody    bool    `json:"log_request_body"`
	EnableTracing     bool    `json:"enable_tracing"`
	EnableMetrics     bool    `json:"enable_metrics"`
	DisableSampling   bool    `json:"disable_sampling"`
}

EnhancedObservabilityConfig holds configuration for the complete observability stack

type HTTPHealthChecker

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

HTTPHealthChecker checks HTTP endpoint health

func NewHTTPHealthChecker

func NewHTTPHealthChecker(name, url string, required bool, timeout time.Duration) *HTTPHealthChecker

func (*HTTPHealthChecker) Check

func (h *HTTPHealthChecker) Check(_ context.Context) error

func (*HTTPHealthChecker) IsRequired

func (h *HTTPHealthChecker) IsRequired() bool

func (*HTTPHealthChecker) Name

func (h *HTTPHealthChecker) Name() string

type HealthCheckConfig

type HealthCheckConfig struct {
	Metrics              observability.MetricsCollector `json:"-"`
	Logger               observability.StructuredLogger `json:"-"`
	Path                 string                         `json:"path"`
	DetailPath           string                         `json:"detail_path"`
	ReadyPath            string                         `json:"ready_path"`
	LivePath             string                         `json:"live_path"`
	Dependencies         []HealthChecker                `json:"-"`
	FailureThreshold     int                            `json:"failure_threshold"`
	RecoveryTime         time.Duration                  `json:"recovery_time"`
	GracePeriod          time.Duration                  `json:"grace_period"`
	Interval             time.Duration                  `json:"interval"`
	Timeout              time.Duration                  `json:"timeout"`
	EnableDetailedChecks bool                           `json:"enable_detailed_checks"`
	EnableMetrics        bool                           `json:"enable_metrics"`
	EnableBackgroundRuns bool                           `json:"enable_background_runs"`
}

HealthCheckConfig holds configuration for health checks

type HealthCheckResult

type HealthCheckResult struct {
	Timestamp time.Time      `json:"timestamp"`
	Details   map[string]any `json:"details,omitempty"`
	Name      string         `json:"name"`
	Status    HealthStatus   `json:"status"`
	Message   string         `json:"message,omitempty"`
	Duration  time.Duration  `json:"duration"`
	Required  bool           `json:"required"`
}

HealthCheckResult represents the result of a health check

type HealthChecker

type HealthChecker interface {
	Name() string
	Check(ctx context.Context) error
	IsRequired() bool // If true, failure marks entire system as unhealthy
}

HealthChecker interface for dependency health checks

type HealthConfig

type HealthConfig = HealthCheckConfig

Backward compatibility aliases

type HealthStatus

type HealthStatus string

HealthStatus represents the health status of a component

const (
	HealthStatusHealthy   HealthStatus = "healthy"
	HealthStatusUnhealthy HealthStatus = "unhealthy"
	HealthStatusDegraded  HealthStatus = "degraded"
	HealthStatusUnknown   HealthStatus = "unknown"
)

type HealthSummary

type HealthSummary struct {
	Total     int `json:"total"`
	Healthy   int `json:"healthy"`
	Unhealthy int `json:"unhealthy"`
	Degraded  int `json:"degraded"`
	Unknown   int `json:"unknown"`
}

HealthSummary provides a summary of health check results

type IdempotencyOptions added in v1.0.27

type IdempotencyOptions struct {
	Store              IdempotencyStore
	OnDuplicate        func(ctx *lift.Context, record *IdempotencyRecord)
	HeaderName         string
	TTL                time.Duration
	ProcessingTimeout  time.Duration
	IncludeRequestHash bool
}

IdempotencyOptions configures the idempotency middleware

type IdempotencyRecord added in v1.0.27

type IdempotencyRecord struct {
	Response  any       `json:"response,omitempty"` // 8 bytes (interface)
	CreatedAt time.Time `json:"created_at"`         // 8 bytes (int64)
	ExpiresAt time.Time `json:"expires_at"`         // 8 bytes (int64)

	Key          string `json:"key"`                     // 16 bytes
	Status       string `json:"status"`                  // "processing", "completed", "error" - 16 bytes
	Error        string `json:"error,omitempty"`         // 16 bytes
	RequestHash  string `json:"request_hash,omitempty"`  // 16 bytes
	FunctionName string `json:"function_name,omitempty"` // 16 bytes
	TenantID     string `json:"tenant_id,omitempty"`     // 16 bytes
	UserID       string `json:"user_id,omitempty"`       // 16 bytes

	StatusCode int `json:"status_code,omitempty"` // 4 bytes
}

IdempotencyRecord represents a stored idempotent response

type IdempotencyStore added in v1.0.27

type IdempotencyStore interface {
	// Get retrieves a stored response by key
	Get(ctx context.Context, key string) (*IdempotencyRecord, error)
	// Set stores a response with the given key
	Set(ctx context.Context, key string, record *IdempotencyRecord) error
	// SetProcessing marks a key as being processed (prevents concurrent duplicates)
	SetProcessing(ctx context.Context, key string, expiresAt time.Time) error
	// Delete removes a key from the store
	Delete(ctx context.Context, key string) error
}

IdempotencyStore defines the interface for storing idempotency keys and responses

type JWTClaims

type JWTClaims struct {
	jwt.RegisteredClaims
	TenantID  string   `json:"tenant_id"`
	AccountID string   `json:"account_id"`
	Roles     []string `json:"roles"`
	Scopes    []string `json:"scopes"`
}

JWTClaims represents the claims in a JWT token

type JWTConfig

type JWTConfig struct {
	PublicKey    any
	Claims       jwt.Claims
	Validator    func(claims jwt.MapClaims) error
	ErrorHandler func(ctx *lift.Context, err error) error
	Extractor    func(ctx *lift.Context) (string, error)
	Secret       string
	Algorithm    string
	TokenLookup  string
	SkipPaths    []string
}

JWTConfig holds configuration for JWT middleware

func DefaultJWTConfig

func DefaultJWTConfig() JWTConfig

DefaultJWTConfig returns a default JWT configuration

type JWTValidator

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

JWTValidator handles JWT token validation

func NewJWTValidator

func NewJWTValidator(config security.JWTConfig) (*JWTValidator, error)

NewJWTValidator creates a new JWT validator

func (*JWTValidator) ValidateToken

func (v *JWTValidator) ValidateToken(tokenString string) (*JWTClaims, error)

ValidateToken validates a JWT token and returns the claims

type LimitedConfig added in v1.0.35

type LimitedConfig struct {
	Logger    *zap.Logger
	Region    string
	TableName string
	Endpoint  string
	Strategy  string
	Window    time.Duration
	Limit     int
}

LimitedConfig holds configuration for the limited-based rate limiter

type LoadMetrics

type LoadMetrics struct {
	LastUpdated         time.Time     `json:"last_updated"`
	WindowStart         time.Time     `json:"window_start"`
	P99Latency          time.Duration `json:"p99_latency"`
	RequestRate         float64       `json:"request_rate"`
	AverageLatency      time.Duration `json:"average_latency"`
	P95Latency          time.Duration `json:"p95_latency"`
	CPUUsage            float64       `json:"cpu_usage"`
	ErrorRate           float64       `json:"error_rate"`
	CurrentSheddingRate float64       `json:"current_shedding_rate"`
	TotalRequests       int64         `json:"total_requests"`
	ShedRequests        int64         `json:"shed_requests"`
	ActiveRequests      int64         `json:"active_requests"`
	MemoryUsage         float64       `json:"memory_usage"`
}

LoadMetrics provides real-time system and application metrics

type LoadSheddingConfig

type LoadSheddingConfig struct {
	Metrics                  observability.MetricsCollector         `json:"-"`
	Logger                   observability.StructuredLogger         `json:"-"`
	SheddingHandler          func(*lift.Context) error              `json:"-"`
	CustomShedder            func(*lift.Context, *LoadMetrics) bool `json:"-"`
	PriorityExtractor        func(*lift.Context) int                `json:"-"`
	LifecycleContext         context.Context                        `json:"-"`
	RegisterStop             func(func())                           `json:"-"`
	PriorityThresholds       map[int]float64                        `json:"priority_thresholds"`
	Strategy                 LoadSheddingStrategy                   `json:"strategy"`
	Name                     string                                 `json:"name"`
	SheddingMessage          string                                 `json:"shedding_message"`
	TargetLatency            time.Duration                          `json:"target_latency"`
	MetricsWindow            time.Duration                          `json:"metrics_window"`
	MetricsCollectorInterval time.Duration                          `json:"-"`
	LatencyThreshold         time.Duration                          `json:"latency_threshold"`
	AdaptationRate           float64                                `json:"adaptation_rate"`
	ErrorRateThreshold       float64                                `json:"error_rate_threshold"`
	MinSheddingRate          float64                                `json:"min_shedding_rate"`
	MaxSheddingRate          float64                                `json:"max_shedding_rate"`
	SamplingRate             float64                                `json:"sampling_rate"`
	SheddingRate             float64                                `json:"shedding_rate"`
	MemoryThreshold          float64                                `json:"memory_threshold"`
	CPUThreshold             float64                                `json:"cpu_threshold"`
	SheddingStatusCode       int                                    `json:"shedding_status_code"`
	EnableMetrics            bool                                   `json:"enable_metrics"`
	Enabled                  bool                                   `json:"enabled"`
}

LoadSheddingConfig holds configuration for load shedding

func ConfigureLoadSheddingForApp added in v1.0.62

func ConfigureLoadSheddingForApp(app *lift.App, config LoadSheddingConfig) LoadSheddingConfig

ConfigureLoadSheddingForApp wires lifecycle management into the provided LoadSheddingConfig using the application's lifecycle context and shutdown hooks when they have not already been supplied.

func NewAdaptiveLoadShedding

func NewAdaptiveLoadShedding(name string, targetLatency time.Duration) LoadSheddingConfig

NewAdaptiveLoadShedding creates an adaptive load shedding configuration

func NewBasicLoadShedding

func NewBasicLoadShedding(name string) LoadSheddingConfig

NewBasicLoadShedding creates a basic load shedding configuration

func NewCustomLoadShedding

func NewCustomLoadShedding(name string, customShedder func(*lift.Context, *LoadMetrics) bool) LoadSheddingConfig

NewCustomLoadShedding creates a custom load shedding configuration

func NewPriorityLoadShedding

func NewPriorityLoadShedding(name string, priorityThresholds map[int]float64) LoadSheddingConfig

NewPriorityLoadShedding creates a priority-based load shedding configuration

type LoadSheddingStats

type LoadSheddingStats struct {
	Strategy            LoadSheddingStrategy `json:"strategy"`
	Name                string               `json:"name"`
	SystemMetrics       LoadMetrics          `json:"system_metrics"`
	TotalRequests       int64                `json:"total_requests"`
	ShedRequests        int64                `json:"shed_requests"`
	AverageLatency      time.Duration        `json:"average_latency"`
	CurrentSheddingRate float64              `json:"current_shedding_rate"`
	SheddingRatio       float64              `json:"shedding_ratio"`
	Enabled             bool                 `json:"enabled"`
}

LoadSheddingStats provides statistics about load shedding performance

type LoadSheddingStrategy

type LoadSheddingStrategy string

LoadSheddingStrategy defines different load shedding strategies

type MemoryHealthChecker

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

MemoryHealthChecker checks memory usage

func NewMemoryHealthChecker

func NewMemoryHealthChecker(name string, threshold float64) *MemoryHealthChecker

func (*MemoryHealthChecker) Check

func (*MemoryHealthChecker) IsRequired

func (m *MemoryHealthChecker) IsRequired() bool

func (*MemoryHealthChecker) Name

func (m *MemoryHealthChecker) Name() string

type MemoryIdempotencyStore added in v1.0.27

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

MemoryIdempotencyStore provides an in-memory implementation of IdempotencyStore This is suitable for single-instance applications or testing Memory optimized: 32 → 8 bytes (24 bytes saved)

func NewMemoryIdempotencyStore added in v1.0.27

func NewMemoryIdempotencyStore() *MemoryIdempotencyStore

NewMemoryIdempotencyStore creates a new in-memory idempotency store

func (*MemoryIdempotencyStore) Delete added in v1.0.27

Delete removes a record

func (*MemoryIdempotencyStore) Get added in v1.0.27

Get retrieves a record by key

func (*MemoryIdempotencyStore) Set added in v1.0.27

Set stores a record

func (*MemoryIdempotencyStore) SetProcessing added in v1.0.27

func (m *MemoryIdempotencyStore) SetProcessing(ctx context.Context, key string, expiresAt time.Time) error

SetProcessing marks a key as being processed

type Middleware

type Middleware func(lift.Handler) lift.Handler

Middleware represents a middleware function

func CORS

func CORS(allowedOrigins []string) Middleware

CORS provides cross-origin resource sharing headers

func Chain

func Chain(middlewares ...Middleware) Middleware

Chain combines multiple middleware into a single middleware

func ErrorHandler

func ErrorHandler() Middleware

ErrorHandler converts errors to appropriate HTTP responses

func Idempotency added in v1.0.27

func Idempotency(opts IdempotencyOptions) Middleware

Idempotency creates middleware that provides idempotent request handling

func Logger

func Logger() Middleware

Logger provides structured request/response logging If no logger is configured on the context, it will initialize a default console logger

func Metrics

func Metrics() Middleware

Metrics collects basic performance metrics

func Recover

func Recover() Middleware

Recover provides panic recovery and graceful error handling

func RequestID

func RequestID() Middleware

RequestID generates and sets a unique request ID

func Timeout

func Timeout(duration time.Duration) Middleware

Timeout adds request timeout handling

type ObservabilityConfig

type ObservabilityConfig struct {
	Logger  observability.StructuredLogger
	Metrics observability.MetricsCollector
	// Optional: custom operation name extractor
	OperationNameFunc func(*lift.Context) string
}

ObservabilityConfig holds configuration for observability middleware

type ObservabilityStats

type ObservabilityStats struct {
	Logger  *observability.LoggerStats  `json:"logger,omitempty"`
	Metrics *observability.MetricsStats `json:"metrics,omitempty"`
	Tracing *TracingStats               `json:"tracing,omitempty"`
}

ObservabilityStats provides comprehensive statistics about observability performance

func GetObservabilityStats

func GetObservabilityStats(config EnhancedObservabilityConfig) ObservabilityStats

GetObservabilityStats returns comprehensive observability statistics

type OverallHealthResult

type OverallHealthResult struct {
	Timestamp   time.Time                     `json:"timestamp"`
	Checks      map[string]*HealthCheckResult `json:"checks,omitempty"`
	Summary     *HealthSummary                `json:"summary,omitempty"`
	Status      HealthStatus                  `json:"status"`
	Version     string                        `json:"version,omitempty"`
	Environment string                        `json:"environment,omitempty"`
	Duration    time.Duration                 `json:"duration"`
}

OverallHealthResult represents the overall system health

type RateLimitConfig

type RateLimitConfig struct {
	DynamORM        *dynamorm.DynamORMWrapper                   `json:"-"`
	ErrorHandler    func(*lift.Context, *RateLimitResult) error `json:"-"`
	KeyFunc         func(*lift.Context) *RateLimitKey           `json:"-"`
	UserLimits      map[string]int                              `json:"user_limits"`
	TenantLimits    map[string]int                              `json:"tenant_limits"`
	Strategy        string                                      `json:"strategy"`
	HeaderPrefix    string                                      `json:"header_prefix"`
	KeyPrefix       string                                      `json:"key_prefix"`
	TableName       string                                      `json:"table_name"`
	BurstLimit      int                                         `json:"burst_limit"`
	Window          time.Duration                               `json:"window"`
	DefaultWindow   time.Duration                               `json:"default_window"`
	CleanupInterval time.Duration                               `json:"cleanup_interval"`
	Granularity     time.Duration                               `json:"granularity"`
	DefaultLimit    int                                         `json:"default_limit"`
	TTL             time.Duration                               `json:"ttl"`
	IncludeMethod   bool                                        `json:"include_method"`
	SkipOptions     bool                                        `json:"skip_options"`
	SkipSuccessful  bool                                        `json:"skip_successful"`
	IncludePath     bool                                        `json:"include_path"`
}

RateLimitConfig holds configuration for rate limiting

type RateLimitEntry

type RateLimitEntry struct {
	WindowStart time.Time `json:"window_start"`
	LastRequest time.Time `json:"last_request"`
	Key         string    `json:"key"`
	Count       int       `json:"count"`
	TTL         int64     `json:"ttl"`
}

RateLimitEntry represents a rate limit record in DynamoDB

type RateLimitKey

type RateLimitKey struct {
	Metadata   map[string]string `json:"metadata"`
	Identifier string            `json:"identifier"`
	Resource   string            `json:"resource"`
	Operation  string            `json:"operation"`
}

RateLimitKey represents a rate limiting key with metadata

type RateLimitResult

type RateLimitResult struct {
	ResetAt     time.Time     `json:"reset_at"`
	WindowStart time.Time     `json:"window_start"`
	Limit       int           `json:"limit"`
	Remaining   int           `json:"remaining"`
	RetryAfter  time.Duration `json:"retry_after"`
	Allowed     bool          `json:"allowed"`
}

RateLimitResult contains the result of a rate limit check

type RateLimitStats

type RateLimitStats struct {
	TotalRequests   int64 `json:"total_requests"`
	AllowedRequests int64 `json:"allowed_requests"`
	BlockedRequests int64 `json:"blocked_requests"`
	ErrorCount      int64 `json:"error_count"`
}

RateLimitStats provides statistics about rate limiting

func GetRateLimitStats

func GetRateLimitStats(config RateLimitConfig) (*RateLimitStats, error)

GetRateLimitStats returns rate limiting statistics from actual usage data

type ResourceStats

type ResourceStats struct {
	ActiveRequests   int     `json:"active_requests"`
	QueuedRequests   int     `json:"queued_requests"`
	TotalRequests    int64   `json:"total_requests"`
	RejectedRequests int64   `json:"rejected_requests"`
	Utilization      float64 `json:"utilization"`
	Limit            int     `json:"limit"`
}

ResourceStats provides statistics for a specific resource pool

type RetryConfig

type RetryConfig struct {
	Metrics                 observability.MetricsCollector                           `json:"-"`
	Logger                  observability.StructuredLogger                           `json:"-"`
	RetryCondition          func(error) bool                                         `json:"-"`
	OnGiveUp                func(attempts int, lastErr error)                        `json:"-"`
	OnRetry                 func(attempt int, err error, delay time.Duration)        `json:"-"`
	CustomBackoff           func(attempt int, lastDelay time.Duration) time.Duration `json:"-"`
	Name                    string                                                   `json:"name"`
	Strategy                RetryStrategy                                            `json:"strategy"`
	NonRetryableErrors      []string                                                 `json:"non_retryable_errors"`
	RetryableErrors         []string                                                 `json:"retryable_errors"`
	RetryableStatusCodes    []int                                                    `json:"retryable_status_codes"`
	NonRetryableStatusCodes []int                                                    `json:"non_retryable_status_codes"`
	MaxAttempts             int                                                      `json:"max_attempts"`
	PerAttemptTimeout       time.Duration                                            `json:"per_attempt_timeout"`
	TotalTimeout            time.Duration                                            `json:"total_timeout"`
	JitterRange             float64                                                  `json:"jitter_range"`
	BackoffMultiplier       float64                                                  `json:"backoff_multiplier"`
	MaxDelay                time.Duration                                            `json:"max_delay"`
	InitialDelay            time.Duration                                            `json:"initial_delay"`
	Jitter                  bool                                                     `json:"jitter"`
	EnableMetrics           bool                                                     `json:"enable_metrics"`
}

RetryConfig holds configuration for the retry middleware

func NewBasicRetry

func NewBasicRetry(name string, maxAttempts int) RetryConfig

NewBasicRetry creates a basic retry configuration with exponential backoff

func NewCustomRetry

func NewCustomRetry(name string, maxAttempts int, backoffFunc func(int, time.Duration) time.Duration) RetryConfig

NewCustomRetry creates a retry configuration with custom backoff

func NewDatabaseRetry

func NewDatabaseRetry(name string, maxAttempts int) RetryConfig

NewDatabaseRetry creates a retry configuration optimized for database operations

func NewHTTPRetry

func NewHTTPRetry(name string, maxAttempts int) RetryConfig

NewHTTPRetry creates a retry configuration optimized for HTTP requests

type RetryStats

type RetryStats struct {
	Name              string        `json:"name"`
	TotalRequests     int64         `json:"total_requests"`
	RetriedRequests   int64         `json:"retried_requests"`
	SuccessfulRetries int64         `json:"successful_retries"`
	FailedRetries     int64         `json:"failed_retries"`
	TotalAttempts     int64         `json:"total_attempts"`
	AverageAttempts   float64       `json:"average_attempts"`
	MaxAttempts       int           `json:"max_attempts"`
	AverageDelay      time.Duration `json:"average_delay"`
	TotalDelay        time.Duration `json:"total_delay"`
}

RetryStats provides statistics about retry performance

type RetryStrategy

type RetryStrategy string

RetryStrategy defines different retry strategies

const (
	RetryStrategyFixed       RetryStrategy = "fixed"       // Fixed delay between retries
	RetryStrategyLinear      RetryStrategy = "linear"      // Linear backoff
	RetryStrategyExponential RetryStrategy = "exponential" // Exponential backoff
	RetryStrategyCustom      RetryStrategy = "custom"      // Custom backoff function
)

type SecurityHeadersConfig

type SecurityHeadersConfig struct {
	CustomHeaders           map[string]string
	ContentSecurityPolicy   string
	XFrameOptions           string
	XXSSProtection          string
	StrictTransportSecurity string
	ReferrerPolicy          string
	PermissionsPolicy       string
	XContentTypeOptions     bool
	IncludeInDevelopment    bool
}

SecurityHeadersConfig configures the security headers middleware

func DefaultSecurityHeadersConfig

func DefaultSecurityHeadersConfig() SecurityHeadersConfig

DefaultSecurityHeadersConfig returns secure default configuration

type ServiceMeshAdapter added in v1.0.37

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

ServiceMeshAdapter provides AWS App Mesh integration Memory optimized: 184 → 168 bytes (16 bytes saved)

func NewServiceMeshAdapter added in v1.0.37

func NewServiceMeshAdapter(meshConfig ServiceMeshConfig) (*ServiceMeshAdapter, error)

NewServiceMeshAdapter creates a new service mesh adapter

func (*ServiceMeshAdapter) DeregisterService added in v1.0.37

func (s *ServiceMeshAdapter) DeregisterService(ctx context.Context) error

DeregisterService removes the service instance from AWS Cloud Map

func (*ServiceMeshAdapter) HealthCheckHandler added in v1.0.37

func (s *ServiceMeshAdapter) HealthCheckHandler() lift.Handler

HealthCheckHandler returns a health check handler

func (*ServiceMeshAdapter) Middleware added in v1.0.37

func (s *ServiceMeshAdapter) Middleware() lift.Middleware

Middleware returns the service mesh middleware

func (*ServiceMeshAdapter) RegisterService added in v1.0.37

func (s *ServiceMeshAdapter) RegisterService(ctx context.Context) error

RegisterService registers the service with AWS Cloud Map

type ServiceMeshConfig added in v1.0.37

type ServiceMeshConfig struct {
	MeshName            string        `json:"mesh_name"`
	VirtualNode         string        `json:"virtual_node"`
	ServiceName         string        `json:"service_name"`
	Namespace           string        `json:"namespace"`
	HealthCheckPath     string        `json:"health_check_path"`
	Port                string        `json:"port"`
	Region              string        `json:"region"`
	HealthCheckInterval time.Duration `json:"health_check_interval"`
	HealthCheckTimeout  time.Duration `json:"health_check_timeout"`
}

ServiceMeshConfig holds configuration for service mesh integration

type ServiceMeshHealthStatus added in v1.0.37

type ServiceMeshHealthStatus struct {
	Dependencies map[string]bool        `json:"dependencies,omitempty"`
	Metadata     map[string]interface{} `json:"metadata,omitempty"`
	Service      string                 `json:"service"`
	VirtualNode  string                 `json:"virtual_node"`
	Healthy      bool                   `json:"healthy"`
}

ServiceMeshHealthStatus represents the health check response for service mesh

type SlidingWindowRateLimiter added in v1.0.37

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

Memory optimized: 32 → 16 bytes (16 bytes saved)

func NewSlidingWindowRateLimiter added in v1.0.37

func NewSlidingWindowRateLimiter(config RateLimitConfig) (*SlidingWindowRateLimiter, error)

func (*SlidingWindowRateLimiter) Middleware added in v1.0.37

func (r *SlidingWindowRateLimiter) Middleware() lift.Middleware

type TimeoutConfig

type TimeoutConfig struct {
	Logger               observability.StructuredLogger    `json:"-"`
	Metrics              observability.MetricsCollector    `json:"-"`
	OperationTimeouts    map[string]time.Duration          `json:"operation_timeouts"`
	TenantTimeouts       map[string]time.Duration          `json:"tenant_timeouts"`
	TimeoutCalculator    func(*lift.Context) time.Duration `json:"-"`
	TimeoutHandler       func(*lift.Context) error         `json:"-"`
	TimeoutMessage       string                            `json:"timeout_message"`
	Name                 string                            `json:"name"`
	DefaultTimeout       time.Duration                     `json:"default_timeout"`
	ReadTimeout          time.Duration                     `json:"read_timeout"`
	WriteTimeout         time.Duration                     `json:"write_timeout"`
	IdleTimeout          time.Duration                     `json:"idle_timeout"`
	ShutdownTimeout      time.Duration                     `json:"shutdown_timeout"`
	TimeoutStatusCode    int                               `json:"timeout_status_code"`
	EnableDynamicTimeout bool                              `json:"enable_dynamic_timeout"`
	GracefulShutdown     bool                              `json:"graceful_shutdown"`
	EnableMetrics        bool                              `json:"enable_metrics"`
}

TimeoutConfig holds configuration for request timeouts

func NewBasicTimeout

func NewBasicTimeout(name string, defaultTimeout time.Duration) TimeoutConfig

NewBasicTimeout creates a basic timeout configuration

func NewDynamicTimeout

func NewDynamicTimeout(name string, defaultTimeout time.Duration, calculator func(*lift.Context) time.Duration) TimeoutConfig

NewDynamicTimeout creates a timeout configuration with dynamic timeout calculation

func NewOperationTimeout

func NewOperationTimeout(name string, defaultTimeout time.Duration, operationTimeouts map[string]time.Duration) TimeoutConfig

NewOperationTimeout creates a timeout configuration with per-operation timeouts

func NewTenantTimeout

func NewTenantTimeout(name string, defaultTimeout time.Duration, tenantTimeouts map[string]time.Duration) TimeoutConfig

NewTenantTimeout creates a timeout configuration with per-tenant timeouts

type TimeoutStats

type TimeoutStats struct {
	Name            string        `json:"name"`
	TotalRequests   int64         `json:"total_requests"`
	TimeoutRequests int64         `json:"timeout_requests"`
	TimeoutRatio    float64       `json:"timeout_ratio"`
	AverageTimeout  time.Duration `json:"average_timeout"`
	MaxTimeout      time.Duration `json:"max_timeout"`
	MinTimeout      time.Duration `json:"min_timeout"`
	AverageDuration time.Duration `json:"average_duration"`
}

TimeoutStats provides statistics about timeout performance

type TracingStats

type TracingStats struct {
	LastTrace       time.Time `json:"last_trace"`
	TracesGenerated int64     `json:"traces_generated"`
	ErrorCount      int64     `json:"error_count"`
}

TracingStats provides statistics about tracing performance

type ValidationConfig

type ValidationConfig struct {
	CustomValidators         map[string]func(string) error `json:"-"`
	AllowedContentTypes      []string                      `json:"allowed_content_types"`
	BlockedUserAgents        []string                      `json:"blocked_user_agents"`
	MaxBodySize              int64                         `json:"max_body_size"`
	MaxHeaderSize            int                           `json:"max_header_size"`
	MaxQueryParamSize        int                           `json:"max_query_param_size"`
	MaxPathParamSize         int                           `json:"max_path_param_size"`
	EnableSQLInjectionCheck  bool                          `json:"enable_sql_injection_check"`
	EnableXSSCheck           bool                          `json:"enable_xss_check"`
	EnablePathTraversalCheck bool                          `json:"enable_path_traversal_check"`
}

ValidationConfig configures input validation middleware

func DefaultValidationConfig

func DefaultValidationConfig() ValidationConfig

DefaultValidationConfig returns a secure default configuration

type WebSocketAuthConfig

type WebSocketAuthConfig struct {
	// 8-byte aligned fields (functions, slices)
	TokenExtractor func(ctx *lift.Context) string           // 8 bytes (function pointer)
	OnError        func(ctx *lift.Context, err error) error // 8 bytes (function pointer)
	SkipRoutes     []string                                 // 24 bytes (slice)

	// Struct field
	JWTConfig security.JWTConfig // struct
}

WebSocketAuthConfig configures WebSocket authentication Memory optimized: 160 → 136 bytes (24 bytes saved)

Jump to

Keyboard shortcuts

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