forked from nownabe/clog
-
Notifications
You must be signed in to change notification settings - Fork 0
/
http_request_test.go
101 lines (93 loc) · 3.29 KB
/
http_request_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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package clog_test
import (
"context"
"testing"
"time"
"go.nownabe.dev/clog"
)
func TestLogger_HTTPReq(t *testing.T) {
t.Parallel()
tests := map[string]struct {
r *clog.HTTPRequest
want map[string]any
}{
"empty": {
r: &clog.HTTPRequest{},
want: buildWantLog("INFO", "HTTP request"),
},
"full": {
r: &clog.HTTPRequest{
RequestMethod: "GET",
RequestURL: "https://example.com/foo",
RequestSize: 123,
Status: 200,
ResponseSize: 456,
UserAgent: "clog",
RemoteIP: "203.0.113.1",
ServerIP: "203.0.113.2",
Referer: "https://example.com/referer",
Latency: 123*time.Second + 456*time.Nanosecond,
CacheLookup: true,
CacheHit: true,
CacheValidatedWithOriginServer: true,
CacheFillBytes: 789,
Protocol: "HTTP/1.1",
},
want: buildWantLog("INFO", "GET https://example.com/foo HTTP/1.1", "httpRequest", map[string]any{
"requestMethod": "GET",
"requestUrl": "https://example.com/foo",
"requestSize": "123",
"status": 200,
"responseSize": "456",
"userAgent": "clog",
"remoteIp": "203.0.113.1",
"serverIp": "203.0.113.2",
"referer": "https://example.com/referer",
"latency": "123.000000456s",
"cacheLookup": true,
"cacheHit": true,
"cacheValidatedWithOriginServer": true,
"cacheFillBytes": "789",
"protocol": "HTTP/1.1",
}),
},
"only requestMethod": {
r: &clog.HTTPRequest{RequestMethod: "GET"},
want: buildWantLog("INFO", "GET", "httpRequest", map[string]any{"requestMethod": "GET"}),
},
"internal error": {
r: &clog.HTTPRequest{RequestMethod: "GET", Status: 500},
want: buildWantLog("ERROR", "GET", "httpRequest", map[string]any{"requestMethod": "GET", "status": 500}),
},
}
ctx := context.Background()
for name, tt := range tests {
tt := tt
t.Run(name, func(t *testing.T) {
t.Parallel()
l, w := newLogger(clog.SeverityInfo)
l.HTTPReq(ctx, tt.r)
w.assertLog(t, tt.want)
})
}
}
func ExampleHTTPReq() {
req := &clog.HTTPRequest{
RequestMethod: "GET",
RequestURL: "https://example.com/foo",
RequestSize: 123,
Status: 200,
ResponseSize: 456,
UserAgent: "clog",
RemoteIP: "203.0.113.1",
ServerIP: "203.0.113.2",
Referer: "https://example.com/referer",
Latency: 123*time.Second + 456*time.Nanosecond,
CacheLookup: true,
CacheHit: true,
CacheValidatedWithOriginServer: true,
CacheFillBytes: 789,
Protocol: "HTTP/1.1",
}
clog.HTTPReq(context.Background(), req, "GET /foo")
}