Request ID¶
Adds unique identifiers to each request for tracing and debugging.
Usage¶
How It Works¶
The middleware:
- Checks for existing
X-Request-IDheader (from upstream proxy) - Generates a new ID if none exists
- Sets
X-Request-IDresponse header - Makes ID available via
c.RequestID()
Example¶
package main
import (
"github.com/gomarten/marten"
"github.com/gomarten/marten/middleware"
)
func main() {
app := marten.New()
app.Use(middleware.RequestID)
app.Use(middleware.Logger)
app.GET("/", func(c *marten.Ctx) error {
return c.OK(marten.M{
"request_id": c.RequestID(),
})
})
app.Run(":8080")
}
Accessing the Request ID¶
// In any handler
func handler(c *marten.Ctx) error {
id := c.RequestID()
// Use in logs
log.Printf("[%s] Processing request", id)
// Include in response
return c.OK(marten.M{"id": id})
}
ID Format¶
- 16-character hexadecimal string
- Generated using crypto/rand
- Example:
a1b2c3d4e5f6g7h8
Use Cases¶
- Request tracing across services
- Correlating logs
- Debugging production issues
- Client-side error reporting
Preserving Upstream IDs¶
If your app is behind a proxy that sets X-Request-ID, the middleware preserves it: