github.com/akm/go-requestid
is a go module for request ID. The package name is requestid
.
It works in the following sequence for each request processing:
- requestid gets request ID from HTTP request header or generates request ID
- requestid create a new context.Context with request ID
- When your application logs with slog.Logger by requestid, the request ID is added to a log record as an attribute.
go get github.com/akm/go-requestid
import "github.com/akm/go-requestid"
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Get the request ID by using requestid.Get in your http handler
requestID := requestid.Get(r.Context())
w.Write([]byte(fmt.Sprintf("Request ID", requestID)))
w.WriteHeader(http.StatusOK)
})
// Wrap your http handler in order to process requestid
handlerWithRequestID := requestid.Wrap(handler)
Setup logger
logger := requestid.NewLoger(slog.NewTextHandler(os.Stdout, nil))
And setup slog Handler for requestid.
See example_test.go for more details.
X-Request-ID
is an unofficial HTTP request/response header. But it is supported by some services, middlewares, frameworks and libraries.
- http.dev / X-Request-ID
- Envoy / Tracing
- nginx / $request_id
- Heroku / HTTP Request IDs
- Ruby on Rails / Action Dispatch RequestId
- django-log-request-id
How to use X-Request-ID
varies depending on the situation.
X-Request-ID
header can be trusted if the application runs behind a proxy such as Envoy or nginx that generates that header.
X-Request-ID
header is unreliable if your application communicates with the client directly or if your proxy does not modify that header.
In the latter case, you should consider using X-Client-Request-ID
.
requestid
provides two ID generators which work with the following packages:
- math/rand/v2
- crypto/rand