middleware.RequestIDFromContext   A
last analyzed

Complexity

Conditions 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2.0625

Importance

Changes 0
Metric Value
cc 2
eloc 5
nop 1
dl 0
loc 8
ccs 3
cts 4
cp 0.75
crap 2.0625
rs 10
c 0
b 0
f 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