Skip to main content

Overview

The requestid middleware generates or propagates unique request IDs for distributed tracing and debugging. Each request gets a unique identifier that can be logged and passed to downstream services.

Installation

Quick Start

Configuration

Examples

Basic Usage

Custom Header

Custom Generator

ID Propagation

If the incoming request has a request ID header, it’s preserved:
If not, a new one is generated:

Logging with Request ID

Pass to Downstream Services

API Reference

Technical Details

Implementation

The requestid middleware is implemented with the following key components:
  • Context Storage: Request IDs are stored in the request context using a private contextKey{} struct type to prevent collisions
  • ID Generation: Default generator creates UUID v4-style identifiers using crypto/rand for cryptographic randomness
  • Header Propagation: The middleware checks for existing request IDs in incoming headers and preserves them, or generates new ones if absent
  • Response Headers: Request IDs are automatically added to response headers for client visibility

UUID v4 Format

The default generator produces IDs in the format: xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx
  • Uses 16 random bytes from crypto/rand
  • Version bits (byte 6): Set to 0x40 to indicate version 4
  • Variant bits (byte 8): Set to 0x80 to indicate RFC 4122 variant 2
  • Final format: 32 hexadecimal characters in 5 groups (8-4-4-4-12)

Context Key Design

The middleware uses a private struct type as the context key:
This prevents accidental key collisions with other middleware or application code that might use string or integer keys.

Flow

  1. Extract request ID from incoming header (if present)
  2. If no header, generate new ID using configured generator
  3. Store ID in request context with private key
  4. Set ID in response header
  5. Continue to next handler

Best Practices

  • Add early in middleware chain
  • Include in all logs
  • Pass to downstream services
  • Use for error correlation

Testing

The middleware includes comprehensive test coverage for all functionality:
  • timing - Performance tracing
  • recover - Panic recovery with context