-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrequest_bench_test.go
More file actions
282 lines (264 loc) · 8.81 KB
/
Copy pathrequest_bench_test.go
File metadata and controls
282 lines (264 loc) · 8.81 KB
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package httpserver
import (
"bytes"
"encoding/json"
"io"
"mime/multipart"
"net/http"
"net/http/httptest"
"net/url"
"testing"
)
// Benchmarks split into two groups so the name reflects what is measured:
// - BenchmarkParser_*: exercises RequestParser via [asTestHTTPHandler],
// measuring parser + tag binding + response write, but NOT the real
// [Router.Handle] / ServeMux dispatch.
// - BenchmarkRouter_*: exercises the full stack via [newTestRouter] +
// ServeMux, including middleware dispatch and the tracker path.
// benchPreflight runs handler once against req and asserts the recorder reports
// wantStatus. It exists so a benchmark cannot silently measure an error path:
// every benchmark must call it (or its router counterpart) before
// [testing.B.ResetTimer].
func benchPreflight(b *testing.B, handler http.HandlerFunc, req *http.Request, wantStatus int) {
b.Helper()
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
if rec.Code != wantStatus {
b.Fatalf("preflight status mismatch: want %d, got %d (body=%q)",
wantStatus, rec.Code, rec.Body.String())
}
}
// benchPreflightRouter is the [Router] counterpart of [benchPreflight]: it
// dispatches through r.serveMux once and asserts the resulting status.
func benchPreflightRouter(b *testing.B, r Router, req *http.Request, wantStatus int) {
b.Helper()
rec := httptest.NewRecorder()
r.serveMux.ServeHTTP(rec, req)
if rec.Code != wantStatus {
b.Fatalf("preflight status mismatch: want %d, got %d (body=%q)",
wantStatus, rec.Code, rec.Body.String())
}
}
// ============ parser-only benchmarks ============
func BenchmarkParser_Query(b *testing.B) {
type Req struct {
Name string `query:"name"`
Age int `query:"age"`
}
handler := asTestHTTPHandler(RequestParser(captureHandler[Req]))
req, _ := http.NewRequest(http.MethodGet, "/?name=alice&age=30", nil)
benchPreflight(b, handler, req, http.StatusOK)
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
}
}
func BenchmarkParser_Header(b *testing.B) {
type Req struct {
Name string `header:"X-Name"`
Age int `header:"X-Age"`
}
handler := asTestHTTPHandler(RequestParser(captureHandler[Req]))
req, _ := http.NewRequest(http.MethodGet, "/", nil)
req.Header.Set("X-Name", "alice")
req.Header.Set("X-Age", "30")
benchPreflight(b, handler, req, http.StatusOK)
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
}
}
func BenchmarkParser_Form(b *testing.B) {
type Req struct {
Name string `form:"name"`
Email string `form:"email"`
}
handler := asTestHTTPHandler(RequestParser(captureHandler[Req]))
formBody := url.Values{"name": {"alice"}, "email": {"alice@example.com"}}.Encode()
makeReq := func() *http.Request {
req, _ := http.NewRequest(http.MethodPost, "/", bytes.NewReader([]byte(formBody)))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.ContentLength = int64(len(formBody))
return req
}
benchPreflight(b, handler, makeReq(), http.StatusOK)
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, makeReq())
}
}
func BenchmarkParser_JSON(b *testing.B) {
type Req struct {
Name string `json:"name"`
Email string `json:"email"`
}
handler := asTestHTTPHandler(RequestParser(captureHandler[Req]))
bodyData, _ := json.Marshal(map[string]string{"name": "alice", "email": "alice@example.com"})
makeReq := func() *http.Request {
req, _ := http.NewRequest(http.MethodPost, "/", bytes.NewReader(bodyData))
req.Header.Set("Content-Type", "application/json")
req.ContentLength = int64(len(bodyData))
return req
}
benchPreflight(b, handler, makeReq(), http.StatusOK)
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, makeReq())
}
}
func BenchmarkParser_Multipart(b *testing.B) {
type Req struct {
Reader *multipartReader `multipart:""`
}
handler := asTestHTTPHandler(RequestParser(captureHandler[Req]))
makeReq := func() *http.Request {
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
field, _ := writer.CreateFormField("name")
_, _ = field.Write([]byte("alice"))
_ = writer.Close()
req, _ := http.NewRequest(http.MethodPost, "/", body)
req.Header.Set("Content-Type", writer.FormDataContentType())
req.ContentLength = int64(body.Len())
return req
}
benchPreflight(b, handler, makeReq(), http.StatusOK)
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, makeReq())
}
}
func BenchmarkParser_RawBody(b *testing.B) {
type Req struct {
Body io.ReadCloser `body:""`
}
handler := asTestHTTPHandler(RequestParser(captureHandler[Req]))
data := []byte("raw body data for benchmarking")
makeReq := func() *http.Request {
req, _ := http.NewRequest(http.MethodPost, "/", bytes.NewReader(data))
req.Header.Set("Content-Type", "application/octet-stream")
req.ContentLength = int64(len(data))
return req
}
benchPreflight(b, handler, makeReq(), http.StatusOK)
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, makeReq())
}
}
func BenchmarkParser_ComplexRequest(b *testing.B) {
type Address struct {
Street string `json:"street" validate:"required"`
City string `json:"city" validate:"required"`
}
type Req struct {
Name string `header:"X-Name" validate:"required"`
Token string `cookie:"session" validate:"required"`
Page int `query:"page" validate:"min=1"`
Address Address `json:"address" validate:"required"`
}
handler := asTestHTTPHandler(RequestParser(captureHandler[Req]))
// Body shape must match the struct: top-level "address" object whose own
// fields match [Address]. A flat body silently binds nothing.
bodyData, _ := json.Marshal(map[string]any{
"address": map[string]string{"street": "123 Main St", "city": "Springfield"},
})
makeReq := func() *http.Request {
req, _ := http.NewRequest(http.MethodPost, "/?page=1", bytes.NewReader(bodyData))
req.Header.Set("X-Name", "alice")
req.Header.Set("Content-Type", "application/json")
req.AddCookie(&http.Cookie{Name: "session", Value: "abc123"})
req.ContentLength = int64(len(bodyData))
return req
}
benchPreflight(b, handler, makeReq(), http.StatusOK)
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, makeReq())
}
}
func BenchmarkParser_Validation(b *testing.B) {
type Req struct {
Name string `query:"name" validate:"required,min=2"`
Email string `query:"email" validate:"required,email"`
Age int `query:"age" validate:"required,min=18,max=120"`
}
handler := asTestHTTPHandler(RequestParser(captureHandler[Req]))
req, _ := http.NewRequest(http.MethodGet, "/?name=alice&email=alice@example.com&age=30", nil)
benchPreflight(b, handler, req, http.StatusOK)
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
}
}
func BenchmarkParser_ResponsePlainText(b *testing.B) {
type Req struct{}
handler := asTestHTTPHandler(RequestParser(func(ctx *Context, _ Req) {
ctx.NewResponse(http.StatusOK).PlainTextBody("hello world")
}))
req, _ := http.NewRequest(http.MethodGet, "/", nil)
benchPreflight(b, handler, req, http.StatusOK)
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
}
}
func BenchmarkParser_ResponseJSON(b *testing.B) {
type Req struct{}
type Data struct {
Name string `json:"name"`
Email string `json:"email"`
Age int `json:"age"`
}
handler := asTestHTTPHandler(RequestParser(func(ctx *Context, _ Req) {
ctx.NewResponse(http.StatusOK).JsonBody(Data{Name: "alice", Email: "alice@example.com", Age: 30})
}))
req, _ := http.NewRequest(http.MethodGet, "/", nil)
benchPreflight(b, handler, req, http.StatusOK)
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
}
}
// ============ Router end-to-end benchmark ============
func BenchmarkRouter_FullStack_WithMiddleware(b *testing.B) {
type Req struct {
Name string `query:"name"`
}
router := newTestRouter()
mw := func(ctx *Context, next func()) { next() }
router.Group(mw).Handle(http.MethodGet+" /", RequestParser(captureHandler[Req]))
req, _ := http.NewRequest(http.MethodGet, "/?name=alice", nil)
benchPreflightRouter(b, router, req, http.StatusOK)
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
rec := httptest.NewRecorder()
router.serveMux.ServeHTTP(rec, req)
}
}