36 lines
710 B
Go
36 lines
710 B
Go
package rest
|
|
|
|
import (
|
|
"context"
|
|
"net/http"
|
|
|
|
"github.com/google/uuid"
|
|
)
|
|
|
|
const requestIDHeader = "X-Request-ID"
|
|
|
|
type requestIDKey struct{}
|
|
|
|
func requestIDFromContext(ctx context.Context) string {
|
|
id, _ := ctx.Value(requestIDKey{}).(string)
|
|
|
|
return id
|
|
}
|
|
|
|
func withRequestID(ctx context.Context, id string) context.Context {
|
|
return context.WithValue(ctx, requestIDKey{}, id)
|
|
}
|
|
|
|
func requestIDMiddleware(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
id := r.Header.Get(requestIDHeader)
|
|
if id == "" {
|
|
id = uuid.NewString()
|
|
}
|
|
|
|
w.Header().Set(requestIDHeader, id)
|
|
|
|
next.ServeHTTP(w, r.WithContext(withRequestID(r.Context(), id)))
|
|
})
|
|
}
|