internal/server/middleware/TracingHandler.go   A
last analyzed

Size/Duplication

Total Lines 44
Duplicated Lines 0 %

Test Coverage

Coverage 90.91%

Importance

Changes 0
Metric Value
cc 5
eloc 23
dl 0
loc 44
ccs 10
cts 11
cp 0.9091
crap 5.0187
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A middleware.TracingHandler 0 2 1
A middleware.RequestIDFromContext 0 8 2
A middleware.*tracingHandler.ServeHTTP 0 11 2
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