23 lines
597 B
Go
23 lines
597 B
Go
|
|
package httpmw
|
||
|
|
|
||
|
|
import (
|
||
|
|
"net/http"
|
||
|
|
|
||
|
|
"code.nochebuena.dev/go/logz"
|
||
|
|
)
|
||
|
|
|
||
|
|
// RequestID injects a unique request ID into the context (via logz.WithRequestID)
|
||
|
|
// and the X-Request-ID response header.
|
||
|
|
// generator is typically uuid.NewString.
|
||
|
|
func RequestID(generator func() string) func(http.Handler) http.Handler {
|
||
|
|
return func(next http.Handler) http.Handler {
|
||
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||
|
|
id := generator()
|
||
|
|
ctx := logz.WithRequestID(r.Context(), id)
|
||
|
|
r = r.WithContext(ctx)
|
||
|
|
w.Header().Set("X-Request-ID", id)
|
||
|
|
next.ServeHTTP(w, r)
|
||
|
|
})
|
||
|
|
}
|
||
|
|
}
|