middleware

package
v0.0.24 Latest Latest
Warning

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

Go to latest
Published: Jan 3, 2025 License: Apache-2.0 Imports: 19 Imported by: 0

Documentation

Overview

Package middleware provides various middleware functions for HTTP handlers.

Package middleware provides various middleware functions for HTTP handlers.

Package middleware provides various middleware functions for HTTP handlers.

Index

Constants

View Source
const (
	RequestIDKey    contextKey = "request_id"
	XTestTimeoutKey contextKey = "X-Test-Timeout"
)

Variables

This section is empty.

Functions

func Authentication added in v0.0.6

func Authentication(next http.Handler) http.Handler

Authentication middleware validates API keys and manages authentication

func CORS

func CORS(next http.Handler) http.Handler

CORS handles Cross-Origin Resource Sharing It allows or denies requests from different origins based on the configuration.

func Logging added in v0.0.7

func Logging(logger *zap.Logger) func(http.Handler) http.Handler

Logging middleware logs request and response details

func PanicRecovery

func PanicRecovery(next http.Handler) http.Handler

PanicRecovery recovers from panics and returns a 500 error

func PrometheusMetrics added in v0.0.9

func PrometheusMetrics(m *metrics.Metrics) func(next http.Handler) http.Handler

PrometheusMetrics middleware records HTTP metrics using Prometheus. It wraps the HTTP handler to measure request duration and active requests. It takes a Metrics object as an argument to track metrics.

func RateLimit added in v0.0.6

func RateLimit(metrics *metrics.Metrics) func(http.Handler) http.Handler

RateLimit creates a new rate limit middleware that applies rate limiting to incoming requests and tracks metrics.

func Recovery added in v0.0.7

func Recovery(logger *zap.Logger) func(http.Handler) http.Handler

Recovery middleware recovers from panics and logs the error It takes a zap.Logger instance for logging errors.

func RequestID

func RequestID(next http.Handler) http.Handler

RequestID middleware adds a unique request ID to the context and sets it in the response header.

func RequestTimer

func RequestTimer(next http.Handler) http.Handler

RequestTimer measures request processing time It wraps the HTTP handler to calculate the duration of the request and sets the X-Response-Time header in the response.

func ResetRateLimiters added in v0.0.7

func ResetRateLimiters()

ResetRateLimiters resets all rate limiters. Only used for testing.

func Timeout added in v0.0.7

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

Timeout middleware adds a timeout to the request context It allows you to specify a duration after which the request will be aborted if not completed.

The Timeout middleware works by creating a new context with a timeout, and using a custom timeoutWriter to track whether a response has been written. If the request times out and no response has been written, it sends a timeout error response.

Types

type QueueConfig added in v0.0.22

type QueueConfig struct {
	InitialSize  int64            // Starting maximum queue size
	Metrics      *metrics.Metrics // Metrics collector for monitoring
	StatePath    string           // Path to store queue state, empty disables persistence
	SaveInterval time.Duration    // How often to save state (0 means no persistence)
}

QueueConfig defines the operational parameters for the queue middleware. These settings control the queue's behavior, capacity, and persistence strategy. Fields: - InitialSize: Starting maximum queue size if no saved state - Metrics: Prometheus metrics collector for monitoring - StatePath: File path for state persistence (empty = no persistence) - SaveInterval: Frequency of state saves (0 = no periodic saves)

type QueueMiddleware added in v0.0.22

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

QueueMiddleware implements a request queue with built-in self-cleaning capabilities. Core Design: 1. Request Lifecycle:

  • Incoming requests are added to a FIFO queue if space is available
  • Each queued request gets a channel that signals its completion
  • When a request completes, its resources are automatically cleaned up
  • Queue position is passed to request context for tracking

2. Self-Cleaning Mechanisms:

  • Channel-based: Each request's done channel is closed on completion
  • Defer-based: Resources are released even if request panics
  • Queue-based: Completed requests are removed from queue automatically
  • Memory-based: Go's GC reclaims unused resources

3. Thread Safety:

  • RWMutex protects queue operations (add/remove)
  • Atomic operations for counters (maxSize, processing)
  • Channel-based synchronization for request completion

4. Health Monitoring:

  • Tracks active requests (queued vs processing)
  • Measures queue wait times and request duration
  • Counts errors (queue full, persistence failures)
  • Monitors queue size against configured maximum

5. State Persistence:

  • Periodic saves of queue state if configured
  • Atomic file operations prevent corruption
  • Automatic recovery on restart

func NewQueueMiddleware added in v0.0.22

func NewQueueMiddleware(cfg QueueConfig) *QueueMiddleware

NewQueueMiddleware initializes a new queue middleware with the given configuration. Initialization Process: 1. Creates queue data structures and channels 2. Attempts to restore previous state if persistence enabled 3. Starts background state persistence if configured 4. Initializes metrics collection

The queue begins accepting requests immediately after initialization. If state persistence is enabled, it will attempt to restore the previous configuration, falling back to InitialSize if no state exists.

func (*QueueMiddleware) GetMaxSize added in v0.0.22

func (qm *QueueMiddleware) GetMaxSize() int64

GetMaxSize returns the current maximum queue size. Thread-safe operation using atomic load.

func (*QueueMiddleware) GetProcessing added in v0.0.22

func (qm *QueueMiddleware) GetProcessing() int32

GetProcessing returns the number of requests currently being processed. Thread-safe operation using atomic load.

func (*QueueMiddleware) GetQueueSize added in v0.0.22

func (qm *QueueMiddleware) GetQueueSize() int

GetQueueSize returns the current queue length. Thread-safe operation protected by mutex.

func (*QueueMiddleware) Handler added in v0.0.22

func (qm *QueueMiddleware) Handler(next http.Handler) http.Handler

Handler manages the request lifecycle through the queue. Request Flow: 1. Queue Check:

  • Verifies space available in queue
  • Rejects request if queue full

2. Request Queuing:

  • Creates completion channel
  • Adds request to queue
  • Updates queue metrics

3. Request Processing:

  • Tracks processing state
  • Passes queue position to request context
  • Forwards request to next handler

4. Automatic Cleanup:

  • Removes request from queue
  • Updates metrics
  • Closes completion channel
  • Records timing metrics

All operations are thread-safe and self-cleaning through defer blocks and channel-based synchronization.

func (*QueueMiddleware) SetMaxSize added in v0.0.22

func (qm *QueueMiddleware) SetMaxSize(size int64)

SetMaxSize updates the maximum number of requests allowed in the queue. Update Process: 1. Atomically updates size limit 2. Triggers async state save if persistence enabled

This is a thread-safe operation that takes effect immediately. New requests will be rejected if queue length reaches the new limit.

func (*QueueMiddleware) Shutdown added in v0.0.22

func (qm *QueueMiddleware) Shutdown(ctx context.Context) error

Shutdown initiates a graceful shutdown of the queue middleware. Shutdown Process: 1. Signals shutdown via done channel 2. Stops periodic state persistence 3. Waits for queued requests to complete (with timeout) 4. Performs final state save

The shutdown will timeout if requests don't complete within 5 seconds, recording a metric and returning an error.

type QueueState added in v0.0.22

type QueueState struct {
	MaxSize     int64     `json:"max_size"`     // Maximum allowed queue size
	QueueLength int       `json:"queue_length"` // Current number of items in queue
	LastSaved   time.Time `json:"last_saved"`   // Timestamp of last save
}

QueueState represents the persistent state of the queue that can be saved and restored. This enables the queue to maintain its configuration across server restarts. Fields: - MaxSize: Maximum number of requests allowed in queue - QueueLength: Number of requests in queue at time of save - LastSaved: Timestamp of last successful save

type ResponseWriter added in v0.0.7

type ResponseWriter struct {
	http.ResponseWriter
	// contains filtered or unexported fields
}

ResponseWriter wraps http.ResponseWriter to capture status code and size

func NewResponseWriter added in v0.0.7

func NewResponseWriter(w http.ResponseWriter) *ResponseWriter

NewResponseWriter creates a new ResponseWriter

func (*ResponseWriter) Size added in v0.0.7

func (w *ResponseWriter) Size() int64

Size returns the response size

func (*ResponseWriter) Status added in v0.0.7

func (w *ResponseWriter) Status() int

Status returns the status code

func (*ResponseWriter) Write added in v0.0.7

func (w *ResponseWriter) Write(b []byte) (int, error)

func (*ResponseWriter) WriteHeader added in v0.0.7

func (w *ResponseWriter) WriteHeader(status int)

Jump to

Keyboard shortcuts

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