Request ID
Attach a request identifier to every response.
Request ID
middleware.RequestID reads or creates a request identifier, stores it on the
request context, and writes it to the response header.
app.Use(middleware.RequestID())The default header is X-Request-ID. A client-provided value is reused. If it
is missing, the middleware generates one.
Options
app.Use(middleware.RequestID(middleware.RequestIDConfig{
Header: "X-Trace-ID",
Length: 24,
Generator: func() string {
return "req-" + time.Now().Format("20060102150405")
},
}))| Option | Default | Description |
|---|---|---|
Header | X-Request-ID | Request and response header name |
Length | 16 | Random bytes generated when no ID is provided |
Generator | random hex | Custom ID generator |
The default generator produces Length random bytes and hex encodes them, so
the visible ID is twice the configured length. If the system random source
fails, it falls back to a process ID and counter value.
Reading the ID
The ID is available in the request session:
app.Get("/", func(c *core.Context) {
id := c.GetSession("request_id")
c.JSON(200, map[string]any{"request_id": id})
})It is also present on the response:
X-Request-ID: 8f14e45fceea167a5a36dedd4bea2543Use with logging
Place RequestID before Logger so every log line can include the same ID.
The current logger prints method, path, and status. If you need the ID in the
line, use a custom middleware around Logger or configure a structured logger
in the application.
Notes
- The middleware does not validate client-provided IDs. Treat them as opaque strings and do not use them for authorization.
- When a trusted edge proxy already sets an ID, keep the default behavior so the proxy value is preserved.
- Use a bounded length for generated IDs. Very large values add unnecessary header and log volume.

Ply