forked from go-chi/chi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
request_id_test.go
71 lines (56 loc) · 1.37 KB
/
request_id_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package middleware
import (
"fmt"
"net/http"
"net/http/httptest"
"testing"
"github.com/go-chi/chi/v5"
)
func maintainDefaultRequestID() func() {
original := RequestIDHeader
return func() {
RequestIDHeader = original
}
}
func TestRequestID(t *testing.T) {
tests := map[string]struct {
requestIDHeader string
request func() *http.Request
expectedResponse string
}{
"Retrieves Request Id from default header": {
"X-Request-Id",
func() *http.Request {
req, _ := http.NewRequest("GET", "/", nil)
req.Header.Add("X-Request-Id", "req-123456")
return req
},
"RequestID: req-123456",
},
"Retrieves Request Id from custom header": {
"X-Trace-Id",
func() *http.Request {
req, _ := http.NewRequest("GET", "/", nil)
req.Header.Add("X-Trace-Id", "trace:abc123")
return req
},
"RequestID: trace:abc123",
},
}
defer maintainDefaultRequestID()()
for _, test := range tests {
w := httptest.NewRecorder()
r := chi.NewRouter()
RequestIDHeader = test.requestIDHeader
r.Use(RequestID)
r.Get("/", func(w http.ResponseWriter, r *http.Request) {
requestID := GetReqID(r.Context())
response := fmt.Sprintf("RequestID: %s", requestID)
w.Write([]byte(response))
})
r.ServeHTTP(w, test.request())
if w.Body.String() != test.expectedResponse {
t.Fatalf("RequestID was not the expected value")
}
}
}