| Total Lines | 44 |
| Duplicated Lines | 0 % |
| Coverage | 90.91% |
| Changes | 0 | ||
| 1 | package middleware |
||
| 2 | |||
| 3 | import ( |
||
| 4 | "context" |
||
| 5 | "net/http" |
||
| 6 | |||
| 7 | "github.com/gofrs/uuid" |
||
| 8 | ) |
||
| 9 | |||
| 10 | type key int |
||
| 11 | |||
| 12 | const ( |
||
| 13 | requestIDKey key = iota |
||
| 14 | ) |
||
| 15 | |||
| 16 | type tracingHandler struct { |
||
| 17 | nextHandler http.Handler |
||
| 18 | } |
||
| 19 | |||
| 20 | func TracingHandler(nextHandler http.Handler) http.Handler { |
||
| 21 | 1 | return &tracingHandler{nextHandler} |
|
| 22 | } |
||
| 23 | |||
| 24 | func (handler *tracingHandler) ServeHTTP(responseWriter http.ResponseWriter, request *http.Request) { |
||
| 25 | 1 | requestID := request.Header.Get("X-Request-Id") |
|
| 26 | |||
| 27 | 1 | if requestID == "" { |
|
| 28 | 1 | requestID = uuid.Must(uuid.NewV4()).String() |
|
| 29 | } |
||
| 30 | |||
| 31 | 1 | ctx := context.WithValue(request.Context(), requestIDKey, requestID) |
|
| 32 | 1 | responseWriter.Header().Set("X-Request-Id", requestID) |
|
| 33 | |||
| 34 | 1 | handler.nextHandler.ServeHTTP(responseWriter, request.WithContext(ctx)) |
|
| 35 | } |
||
| 36 | |||
| 37 | func RequestIDFromContext(ctx context.Context) string { |
||
| 38 | 1 | id, exists := ctx.Value(requestIDKey).(string) |
|
| 39 | |||
| 40 | 1 | if !exists { |
|
| 41 | id = uuid.Nil.String() |
||
| 42 | } |
||
| 43 | |||
| 44 | 1 | return id |
|
| 45 | } |
||
| 46 |