middleware

package
v0.11.0 Latest Latest
Warning

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

Go to latest
Published: Feb 15, 2025 License: MIT Imports: 18 Imported by: 0

Documentation

Index

Constants

View Source
const DefaultRequestIDHeader = "X-Request-ID"

DefaultRequestIDHeader is the default header name where the request ID is stored.

Variables

This section is empty.

Functions

func CircuitBreaker

func CircuitBreaker(opts ...CircuitBreakerOption) gin.HandlerFunc

CircuitBreaker creates a Gin middleware that wraps route handlers with a circuit breaker.

This middleware monitors request failures and automatically trips the circuit breaker when failures exceed a configured threshold. Once tripped, requests are blocked and a fallback error response is returned until the circuit breaker recovers.

Features:

  • Failure Detection: Automatically detects failures based on HTTP status codes or custom logic.
  • Customizable Behavior: Configure the circuit breaker settings, error thresholds, and fallback handlers.
  • Selective Application: Use filters to apply the circuit breaker only to specific routes or requests.

Example Usage:

CircuitBreaker(
	WithCircuitBreakerSettings(gobreaker.Settings{
		Name: "CustomCircuitBreaker",
		ReadyToTrip: func(counts gobreaker.Counts) bool {
			return counts.ConsecutiveFailures > 3 // Trip after 3 consecutive failures.
		},
	}),
	WithCircuitBreakerStatusThreshold(http.StatusBadRequest), // Treat >= 400 as errors.
	WithCircuitBreakerErrorHandler(func(c *gin.Context) {
		// Custom error handler for circuit breaker failures.
		c.AbortWithStatusJSON(http.StatusServiceUnavailable, gin.H{
			"error": "Custom error: Circuit breaker activated.",
		})
	}),
	WithCircuitBreakerFilter(func(req *http.Request) bool {
		return req.URL.Path != "/health" // Skip circuit breaker for health checks.
	}),
),

func ConfigureDefaultMiddlewares added in v0.11.0

func ConfigureDefaultMiddlewares(config DefaultMiddlewareConfig) []gin.HandlerFunc

ConfigureDefaultMiddlewares returns a slice of Gin handlers that constitute a standardized "default" middleware chain for common features. These include:

  • Recovery: Recovers from panics and returns a 500 Internal Server Error response.
  • CircuitBreaker: Monitors request failures and may trip to protect the service.
  • Trace: Instruments incoming requests with OpenTelemetry spans if a TracerProvider is given.
  • RequestID: Ensures each request has a unique identifier (injected in the header and context).
  • RequestLogger: Logs incoming requests with metadata such as method, route, and status code.

The behavior of certain middlewares (e.g., tracing, logging) is influenced by the fields in DefaultMiddlewareConfig. If the TracerProvider is nil, the global trace provider is used. If the Logger is nil, a default logger is used.

Example usage:

cfg := DefaultMiddlewareConfig{
  Logger:         myLogger,
  TracerProvider: myTracerProvider,
}

router := gin.New()
router.Use(ConfigureDefaultMiddlewares(cfg)...)

func GetRequestIDFromContext

func GetRequestIDFromContext(ctx context.Context) (string, bool)

GetRequestIDFromContext retrieves the request ID from the context.

func Recovery

func Recovery(opts ...RecoveryOption) gin.HandlerFunc

Recovery returns a Gin middleware that recovers from panics during request handling and logs the error.

The middleware performs the following tasks:

  1. Recovers from any panic that occurs in the middleware chain or route handlers.
  2. Logs the panic information (including HTTP method and route) using the provided logger or retrieves one from the context.
  3. Calls a custom error handler to generate a response, or defaults to a 500 Internal Server Error response if no custom handler is provided.

Key Features:

  • Custom Logger: Use `WithRecoveryLogger` to specify a logger for capturing panic details. If no logger is provided, the middleware attempts to retrieve one from the context.
  • Custom Error Handler: Use `WithRecoveryHandler` to define a custom function for handling the panic and responding to the client.
  • Default Behavior: If no logger or custom handler is specified, the middleware logs the panic (using the context logger) and returns a 500 Internal Server Error response.

Example Usage:

router.Use(
	Recovery(
    	WithRecoveryLogger(logger), // Use a custom logger for panic recovery.
    	WithRecoveryHandler(func(c *gin.Context, err interface{}) {
        	// Custom error handling logic (e.g., custom JSON response).
        	c.AbortWithStatusJSON(
				http.StatusInternalServerError,
				gin.H{"message": "Something went wrong. Please contact support.", "details": err}
			)
    	}),
	),
)

func RequestID

func RequestID(opts ...RequestIDOption) gin.HandlerFunc

RequestID returns a Gin middleware that injects a unique request ID into each HTTP request's context.

The middleware performs the following tasks:

  1. Extracts the request ID from the incoming request headers using the specified header name (default: "X-Request-ID").
  2. Validates the request ID to ensure it is not empty and does not exceed 64 characters. If invalid or missing, it generates a new request ID using the provided or default generator function.
  3. Sets the request ID in the response headers so that the client knows which request ID was assigned.
  4. Stores the request ID in the request context, making it accessible to downstream middlewares and handlers.

Key Features:

  • Custom Header Name: Use `WithRequestIDHeader` to specify a custom header name for the request ID.
  • Custom ID Generator: Use `WithRequestIDGenerator` or `WithRequestIDContextGenerator` to provide a custom generator function for creating request IDs.
  • Default Generator: By default, the middleware uses the `xid` package to generate compact and globally unique request IDs.
  • Request Context Integration: The request ID is injected into the context, enabling downstream handlers to retrieve it using `GetRequestIDFromContext`.

Example Usage:

router.Use(
	RequestID(
    	WithRequestIDHeader("X-Custom-Request-ID"), // Use a custom header name.
    	WithRequestIDGenerator(func() string {     // Use a custom generator function.
        	return "custom-" + xid.New().String()
    	}),
	),
)

func RequestLogger

func RequestLogger(opts ...RequestLoggerOption) gin.HandlerFunc

RequestLogger returns a Gin middleware that logs detailed information about HTTP requests and responses. It also augments the logger with request-specific fields and stores it in the context for downstream handlers.

Functionality:

  • Logs request details, such as method, route, query parameters, client IP, and user agent.
  • Measures and logs the request latency and response status code.
  • Allows filtering of requests to determine whether they should be logged.
  • Injects an augmented logger with request-specific fields into the request context for downstream use.

Key Features:

  • Custom Logger: Use `WithRequestLogger` to provide a custom logger. If not provided, a default logger is used.
  • Request Filters: Use `WithRequestLoggerFilter` to specify one or more filters. Requests that do not pass the filters will not be logged.
  • Request Context Integration: The middleware adds an augmented logger to the request context, allowing downstream handlers to use it for logging.

Example Usage:

router.Use(
	RequestLogger(
		WithRequestLogger(customLogger), // Use a custom logger.
		WithRequestLoggerFilter(func(req *http.Request) bool {
			// Skip logging for health check routes.
			return req.URL.Path != "/health"
		}),
	),
)

func Trace

func Trace(options ...TraceOption) gin.HandlerFunc

Trace is a Gin middleware that integrates OpenTelemetry tracing into the request lifecycle. The middleware creates a span for each incoming HTTP request and attaches it to the request context.

The middleware performs the following actions:

  1. Initializes tracing options using the provided TraceOption functions or falls back to defaults. - If no tracer provider is provided, it uses the global tracer provider from OpenTelemetry. - If no propagators are specified, it uses the global text map propagators.
  2. Applies user-defined filters to determine whether a request should be traced.
  3. Extracts tracing context from the incoming request headers using the specified propagators.
  4. Determines the span name using a custom formatter or defaults to "<METHOD> <PATH>".
  5. Creates a new span and adds common HTTP attributes to the span (e.g., method, path, client IP).
  6. Passes the span context through the request for use by downstream handlers and middlewares.
  7. Records errors and sets the span status based on the HTTP response status code.
  8. Ends the span once the request processing is complete.

Example Usage:

router.Use(
    Trace(
        WithTracerProvider(tracerProvider),
        WithTracePropagators(propagators),
        WithTraceFilter(func(req *http.Request) bool {
            return req.Method != http.MethodOptions // Skip OPTIONS requests
        }),
        WithSpanNameFormatter(func(req *http.Request) string {
            return fmt.Sprintf("CustomSpanName %s %s", req.Method, req.URL.Path)
        }),
    ),
)

Types

type CircuitBreakerFilter

type CircuitBreakerFilter func(*http.Request) bool

CircuitBreakerFilter is a function that determines whether a request should be wrapped by the circuit breaker.

type CircuitBreakerOption

type CircuitBreakerOption func(*circuitBreakerOptions)

CircuitBreakerOption is a function that configures circuitBreakerOptions.

func WithCircuitBreakerErrorHandler

func WithCircuitBreakerErrorHandler(handler func(c *gin.Context)) CircuitBreakerOption

WithCircuitBreakerErrorHandler sets a custom error handler for circuit breaker failures.

func WithCircuitBreakerFilter

func WithCircuitBreakerFilter(filters ...CircuitBreakerFilter) CircuitBreakerOption

WithCircuitBreakerFilter adds one or more filters to determine whether the circuit breaker applies to specific requests.

func WithCircuitBreakerSettings

func WithCircuitBreakerSettings(settings gobreaker.Settings) CircuitBreakerOption

WithCircuitBreakerSettings allows customizing the circuit breaker settings.

func WithCircuitBreakerStatusThreshold

func WithCircuitBreakerStatusThreshold(threshold int) CircuitBreakerOption

WithCircuitBreakerStatusThreshold sets the status code threshold for error detection.

type DefaultMiddlewareConfig added in v0.11.0

type DefaultMiddlewareConfig struct {
	Logger         common_logger.Logger
	TracerProvider trace.TracerProvider
}

type RecoveryOption

type RecoveryOption func(*recoveryOptions)

RecoveryOptions is a function that configures recoveryOptions.

func WithRecoveryHandler

func WithRecoveryHandler(handler func(c *gin.Context, err interface{})) RecoveryOption

WithRecoveryHandler sets a custom error handler for the Recovery middleware.

func WithRecoveryLogger

func WithRecoveryLogger(logger common_logger.Logger) RecoveryOption

WithLogger sets a custom logger for the Recovery middleware.

type RequestIDContextGenerator added in v0.11.0

type RequestIDContextGenerator func(c *gin.Context) string

RequestIDContextGenerator is a function type that generates a unique ID based on the Gin context.

type RequestIDGenerator

type RequestIDGenerator func() string

RequestIDGenerator is a function type that generates a unique ID.

type RequestIDOption

type RequestIDOption func(*requestIDOptions)

RequestIDOption is a function that configures the requestIDOptions.

func WithRequestIDContextGenerator added in v0.11.0

func WithRequestIDContextGenerator(gen RequestIDContextGenerator) RequestIDOption

WithRequestIDContextGenerator allows setting a custom ID generator function that uses the Gin context.

func WithRequestIDGenerator

func WithRequestIDGenerator(gen RequestIDGenerator) RequestIDOption

WithRequestIDGenerator allows setting a custom ID generator function.

func WithRequestIDHeader

func WithRequestIDHeader(headerName string) RequestIDOption

WithRequestIDHeader allows setting a custom header name for the request ID.

type RequestLoggerFilter

type RequestLoggerFilter func(*http.Request) bool

RequestLoggerFilter is a function that determines whether a request should be logged. It returns true if the request should be logged.

type RequestLoggerOption

type RequestLoggerOption func(*requestLoggerOptions)

RequestLoggerOption is a function that configures requestLoggerOptions.

func WithRequestLogger

func WithRequestLogger(logger common_logger.Logger) RequestLoggerOption

WithRequestLogger allows setting a custom logger for the request logger middleware.

func WithRequestLoggerFilter

func WithRequestLoggerFilter(filters ...RequestLoggerFilter) RequestLoggerOption

WithRequestLoggerFilter adds one or more filters to the list of filters used by the request logger middleware.

type SpanNameFormatter

type SpanNameFormatter func(*http.Request) string

SpanNameFormatter is used to set the span name based on the http.Request.

type TraceFilter

type TraceFilter func(*http.Request) bool

TraceFilter is a function that determines whether a request should be traced. It returns true if the request should be traced.

type TraceOption

type TraceOption func(*traceOptions)

TraceOption specifies instrumentation configuration options.

func WithSpanNameFormatter

func WithSpanNameFormatter(formatter SpanNameFormatter) TraceOption

WithSpanNameFormatter sets a custom function to format the span name for each request.

func WithTraceFilter

func WithTraceFilter(filters ...TraceFilter) TraceOption

WithTraceFilter adds one or more filters to the list of filters used by the middleware.

func WithTracePropagators

func WithTracePropagators(propagators propagation.TextMapPropagator) TraceOption

WithTracePropagators specifies propagators to use for extracting information from the HTTP requests.

func WithTracerProvider

func WithTracerProvider(provider oteltrace.TracerProvider) TraceOption

WithTracerProvider specifies a tracer provider to use for creating a tracer.

Jump to

Keyboard shortcuts

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