39 lines
1.1 KiB
Go
39 lines
1.1 KiB
Go
|
package middleware
|
||
|
|
||
|
import (
|
||
|
"net/http"
|
||
|
|
||
|
"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()
|
||
|
}
|
||
|
|
||
|
// XXX: Add request_id to the context, push the context to r & edit logger middleware to add the request_id as fields
|
||
|
|
||
|
// 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,
|
||
|
}
|
||
|
}
|