42 lines
1.1 KiB
Go
42 lines
1.1 KiB
Go
package middleware
|
|
|
|
import (
|
|
"net/http"
|
|
|
|
"git.dev.m-and-m.ovh/mderasse/gocommon/commonctx"
|
|
"github.com/google/uuid"
|
|
)
|
|
|
|
const requestIDHeaderKey = "X-Request-ID"
|
|
|
|
type requestIDMiddleware struct {
|
|
handler http.Handler
|
|
}
|
|
|
|
func (rm *requestIDMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|
requestID := r.Header.Get(requestIDHeaderKey)
|
|
if _, err := uuid.Parse(requestID); err != nil {
|
|
// no request ID or invalid. let's generate a new one
|
|
requestID = uuid.New().String()
|
|
}
|
|
|
|
// add requestID to context and update request
|
|
ctx := commonctx.AddRequestID(r.Context(), requestID)
|
|
r = r.WithContext(ctx)
|
|
|
|
// add the request ID to the response query
|
|
w.Header().Set(requestIDHeaderKey, requestID)
|
|
|
|
// and exec the next handler
|
|
rm.handler.ServeHTTP(w, r)
|
|
}
|
|
|
|
// NewRequestIDMiddleware will declare a new middleware on the provided handler. It will analyse the incoming
|
|
// query to find a x-request-id header. It will had it to the response and also to the context.
|
|
// If request-id header doesn't exist. A new one will be generated.
|
|
func NewRequestIDMiddleware(h http.Handler) http.Handler {
|
|
return &requestIDMiddleware{
|
|
handler: h,
|
|
}
|
|
}
|