Debian Codegraph @

gzhttp/compress_test.go

raw
1 package gzhttp
2
3 import (
4 "bytes"
5 "context"
6 "fmt"
7 "io"
8 "math/rand"
9 "net"
10 "net/http"
11 "net/http/httptest"
12 "net/http/httptrace"
13 "net/textproto"
14 "net/url"
15 "os"
16 "strconv"
17 "strings"
18 "testing"
19
20 "github.com/klauspost/compress/gzip"
21 "github.com/klauspost/compress/zstd"
22 )
23
24 var (
25 smallTestBody = []byte("aaabbcaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbc")
26 testBody = []byte("aaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbccc aaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbccc aaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbccc aaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbccc aaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbccc aaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbccc aaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbcccaaabbbccc")
27 )
28
29 func TestParseEncodings(t *testing.T) {
30 examples := map[string]codings{
31
32 // Examples from RFC 2616
33 "compress, gzip": {"compress": 1.0, "gzip": 1.0},
34 ",,,,": {},
35 "": {},
36 "*": {"*": 1.0},
37 "compress;q=0.5, gzip;q=1.0": {"compress": 0.5, "gzip": 1.0},
38 "gzip;q=1.0, identity; q=0.5, *;q=0": {"gzip": 1.0, "identity": 0.5, "*": 0.0},
39
40 // More random stuff
41 "AAA;q=1": {"aaa": 1.0},
42 "BBB ; q = 2": {"bbb": 1.0},
43
44 "gzip;q=0.5;level=6": {"gzip": 0.5},
45 "gzip;q=0.3;level=6;x=y": {"gzip": 0.3},
46
47 "gzip;Q=0.5": {"gzip": 0.5},
48 "GZIP;Q=0.7": {"gzip": 0.7},
49 "gzip;Q=0.4;x=y": {"gzip": 0.4},
50 }
51
52 for eg, exp := range examples {
53 t.Run(eg, func(t *testing.T) {
54 act, _ := parseEncodings(eg)
55 assertEqual(t, exp, act)
56 gz := parseEncodingGzip(eg)
57 assertEqual(t, exp["gzip"], gz)
58 })
59 }
60 }
61
62 func TestMustNewGzipHandler(t *testing.T) {
63 // This just exists to provide something for GzipHandler to wrap.
64 handler := newTestHandler(testBody)
65
66 // requests without accept-encoding are passed along as-is
67
68 req1, _ := http.NewRequest("GET", "/whatever", nil)
69 resp1 := httptest.NewRecorder()
70 handler.ServeHTTP(resp1, req1)
71 res1 := resp1.Result()
72
73 assertEqual(t, 200, res1.StatusCode)
74 assertEqual(t, "", res1.Header.Get("Content-Encoding"))
75 assertEqual(t, "Accept-Encoding", res1.Header.Get("Vary"))
76 assertEqual(t, testBody, resp1.Body.Bytes())
77
78 // but requests with accept-encoding:gzip are compressed if possible
79
80 req2, _ := http.NewRequest("GET", "/whatever", nil)
81 req2.Header.Set("Accept-Encoding", "gzip")
82 resp2 := httptest.NewRecorder()
83 handler.ServeHTTP(resp2, req2)
84 res2 := resp2.Result()
85
86 assertEqual(t, 200, res2.StatusCode)
87 assertEqual(t, "gzip", res2.Header.Get("Content-Encoding"))
88 assertEqual(t, "Accept-Encoding", res2.Header.Get("Vary"))
89 assertEqual(t, gzipStrLevel(testBody, gzip.DefaultCompression), resp2.Body.Bytes())
90
91 // content-type header is correctly set based on uncompressed body
92
93 req3, _ := http.NewRequest("GET", "/whatever", nil)
94 req3.Header.Set("Accept-Encoding", "gzip")
95 res3 := httptest.NewRecorder()
96 handler.ServeHTTP(res3, req3)
97
98 assertEqual(t, http.DetectContentType([]byte(testBody)), res3.Header().Get("Content-Type"))
99
100 // send compress request body with `AllowCompressedRequests`
101 handler = newTestHandlerLevel(testBody, AllowCompressedRequests(true))
102
103 var b bytes.Buffer
104 writerGzip := gzip.NewWriter(&b)
105 writerGzip.Write(testBody)
106 writerGzip.Close()
107
108 req5, _ := http.NewRequest("POST", "/whatever", &b)
109 req5.Header.Set("Content-Encoding", "gzip")
110 resp5 := httptest.NewRecorder()
111 handler.ServeHTTP(resp5, req5)
112 res5 := resp5.Result()
113
114 assertEqual(t, 200, res5.StatusCode)
115
116 body, _ := io.ReadAll(res5.Body)
117 assertEqual(t, len(testBody), len(body))
118
119 // send compress request body without `AllowCompressedRequests`
120 writerGzip = gzip.NewWriter(&b)
121 writerGzip.Write(testBody)
122 writerGzip.Close()
123
124 handler = newTestHandlerLevel(b.Bytes())
125
126 req6, _ := http.NewRequest("POST", "/whatever", &b)
127 resp6 := httptest.NewRecorder()
128 handler.ServeHTTP(resp6, req6)
129 res6 := resp6.Result()
130
131 assertEqual(t, 200, res6.StatusCode)
132 body, _ = io.ReadAll(res6.Body)
133 assertEqual(t, b.Len(), len(body))
134 }
135
136 func TestGzipHandlerSmallBodyNoCompression(t *testing.T) {
137 handler := newTestHandler(smallTestBody)
138
139 req, _ := http.NewRequest("GET", "/whatever", nil)
140 req.Header.Set("Accept-Encoding", "gzip")
141 resp := httptest.NewRecorder()
142 handler.ServeHTTP(resp, req)
143 res := resp.Result()
144
145 // with less than 1400 bytes the response should not be gzipped
146
147 assertEqual(t, 200, res.StatusCode)
148 assertEqual(t, "", res.Header.Get("Content-Encoding"))
149 assertEqual(t, "Accept-Encoding", res.Header.Get("Vary"))
150 assertEqual(t, smallTestBody, resp.Body.Bytes())
151
152 }
153
154 func TestGzipHandlerAlreadyCompressed(t *testing.T) {
155 handler := newTestHandler(testBody)
156
157 req, _ := http.NewRequest("GET", "/gzipped", nil)
158 req.Header.Set("Accept-Encoding", "gzip")
159 res := httptest.NewRecorder()
160 handler.ServeHTTP(res, req)
161
162 assertEqual(t, testBody, res.Body.Bytes())
163 }
164
165 func TestGzipHandlerRangeReply(t *testing.T) {
166 handler := GzipHandler(
167 http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
168 w.Header().Set("Content-Range", "bytes 0-300/804")
169 w.WriteHeader(http.StatusOK)
170 w.Write([]byte(testBody))
171 }))
172 req, _ := http.NewRequest("GET", "/gzipped", nil)
173 req.Header.Set("Accept-Encoding", "gzip")
174
175 resp := httptest.NewRecorder()
176 handler.ServeHTTP(resp, req)
177 res := resp.Result()
178 assertEqual(t, 200, res.StatusCode)
179 assertEqual(t, "", res.Header.Get("Content-Encoding"))
180 assertEqual(t, testBody, resp.Body.Bytes())
181 }
182
183 func TestGzipHandlerAcceptRange(t *testing.T) {
184 handler := GzipHandler(
185 http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
186 w.Header().Set("Accept-Ranges", "bytes")
187 w.WriteHeader(http.StatusOK)
188 w.Write([]byte(testBody))
189 }))
190 req, _ := http.NewRequest("GET", "/gzipped", nil)
191 req.Header.Set("Accept-Encoding", "gzip")
192
193 resp := httptest.NewRecorder()
194 handler.ServeHTTP(resp, req)
195 res := resp.Result()
196 assertEqual(t, 200, res.StatusCode)
197 assertEqual(t, "gzip", res.Header.Get("Content-Encoding"))
198 assertEqual(t, "", res.Header.Get("Accept-Ranges"))
199 zr, err := gzip.NewReader(resp.Body)
200 assertNil(t, err)
201 got, err := io.ReadAll(zr)
202 assertNil(t, err)
203 assertEqual(t, testBody, got)
204 }
205
206 func TestGzipHandlerKeepAcceptRange(t *testing.T) {
207 wrapper, err := NewWrapper(KeepAcceptRanges())
208 assertNil(t, err)
209 handler := wrapper(
210 http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
211 w.Header().Set("Accept-Ranges", "bytes")
212 w.WriteHeader(http.StatusOK)
213 w.Write([]byte(testBody))
214 }))
215 req, _ := http.NewRequest("GET", "/gzipped", nil)
216 req.Header.Set("Accept-Encoding", "gzip")
217
218 resp := httptest.NewRecorder()
219 handler.ServeHTTP(resp, req)
220 res := resp.Result()
221 assertEqual(t, 200, res.StatusCode)
222 assertEqual(t, "gzip", res.Header.Get("Content-Encoding"))
223 assertEqual(t, "bytes", res.Header.Get("Accept-Ranges"))
224 zr, err := gzip.NewReader(resp.Body)
225 assertNil(t, err)
226 got, err := io.ReadAll(zr)
227 assertNil(t, err)
228 assertEqual(t, testBody, got)
229 }
230
231 func TestGzipHandlerSuffixETag(t *testing.T) {
232 wrapper, err := NewWrapper(SuffixETag("-gzip"))
233 assertNil(t, err)
234
235 handlerWithETag := wrapper(
236 http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
237 w.Header().Set("Etag", `W/"1234"`)
238 w.WriteHeader(http.StatusOK)
239 w.Write([]byte(testBody))
240 }))
241 handlerWithoutETag := wrapper(
242 http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
243 w.WriteHeader(http.StatusOK)
244 w.Write([]byte(testBody))
245 }))
246
247 req, _ := http.NewRequest("GET", "/gzipped", nil)
248 req.Header.Set("Accept-Encoding", "gzip")
249
250 respWithEtag := httptest.NewRecorder()
251 respWithoutEtag := httptest.NewRecorder()
252 handlerWithETag.ServeHTTP(respWithEtag, req)
253 handlerWithoutETag.ServeHTTP(respWithoutEtag, req)
254
255 resWithEtag := respWithEtag.Result()
256 assertEqual(t, 200, resWithEtag.StatusCode)
257 assertEqual(t, "gzip", resWithEtag.Header.Get("Content-Encoding"))
258 assertEqual(t, `W/"1234-gzip"`, resWithEtag.Header.Get("Etag"))
259 zr, err := gzip.NewReader(resWithEtag.Body)
260 assertNil(t, err)
261 got, err := io.ReadAll(zr)
262 assertNil(t, err)
263 assertEqual(t, testBody, got)
264
265 resWithoutEtag := respWithoutEtag.Result()
266 assertEqual(t, 200, resWithoutEtag.StatusCode)
267 assertEqual(t, "gzip", resWithoutEtag.Header.Get("Content-Encoding"))
268 assertEqual(t, "", resWithoutEtag.Header.Get("Etag"))
269 zr, err = gzip.NewReader(resWithoutEtag.Body)
270 assertNil(t, err)
271 got, err = io.ReadAll(zr)
272 assertNil(t, err)
273 assertEqual(t, testBody, got)
274 }
275
276 func TestGzipHandlerDropETag(t *testing.T) {
277 wrapper, err := NewWrapper(DropETag())
278 assertNil(t, err)
279
280 handlerCompressed := wrapper(
281 http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
282 w.Header().Set("Etag", `W/"1234"`)
283 w.WriteHeader(http.StatusOK)
284 w.Write([]byte(testBody))
285 }))
286 handlerUncompressed := wrapper(
287 http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
288 w.Header().Set("Etag", `W/"1234"`)
289 w.Header().Set(HeaderNoCompression, "true")
290 w.WriteHeader(http.StatusOK)
291 w.Write([]byte(testBody))
292 }))
293
294 req, _ := http.NewRequest("GET", "/gzipped", nil)
295 req.Header.Set("Accept-Encoding", "gzip")
296
297 respCompressed := httptest.NewRecorder()
298 respUncompressed := httptest.NewRecorder()
299 handlerCompressed.ServeHTTP(respCompressed, req)
300 handlerUncompressed.ServeHTTP(respUncompressed, req)
301
302 resCompressed := respCompressed.Result()
303 assertEqual(t, 200, resCompressed.StatusCode)
304 assertEqual(t, "gzip", resCompressed.Header.Get("Content-Encoding"))
305 assertEqual(t, "", resCompressed.Header.Get("Etag"))
306 zr, err := gzip.NewReader(resCompressed.Body)
307 assertNil(t, err)
308 got, err := io.ReadAll(zr)
309 assertNil(t, err)
310 assertEqual(t, testBody, got)
311
312 resUncompressed := respUncompressed.Result()
313 assertEqual(t, 200, resUncompressed.StatusCode)
314 assertEqual(t, "", resUncompressed.Header.Get("Content-Encoding"))
315 assertEqual(t, `W/"1234"`, resUncompressed.Header.Get("Etag"))
316 got, err = io.ReadAll(resUncompressed.Body)
317 assertNil(t, err)
318 assertEqual(t, testBody, got)
319 }
320
321 func TestSuffixETagEncodingSpecific(t *testing.T) {
322 tests := []struct {
323 name string
324 suffix string
325 acceptEncoding string
326 wantETag string
327 }{
328 {"gzip-with-gzip-suffix", "-gzip", "gzip", `W/"1234-gzip"`},
329 {"zstd-with-gzip-suffix", "-gzip", "zstd", `W/"1234-zstd"`},
330 {"gzip-with-custom-suffix", "-compressed", "gzip", `W/"1234-compressed-gzip"`},
331 {"zstd-with-custom-suffix", "-compressed", "zstd", `W/"1234-compressed-zstd"`},
332 }
333
334 for _, tt := range tests {
335 t.Run(tt.name, func(t *testing.T) {
336 wrapper, err := NewWrapper(SuffixETag(tt.suffix))
337 assertNil(t, err)
338
339 handler := wrapper(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
340 w.Header().Set("Etag", `W/"1234"`)
341 w.Write(testBody)
342 }))
343
344 req, _ := http.NewRequest("GET", "/", nil)
345 req.Header.Set("Accept-Encoding", tt.acceptEncoding)
346 resp := httptest.NewRecorder()
347 handler.ServeHTTP(resp, req)
348
349 res := resp.Result()
350 assertEqual(t, tt.wantETag, res.Header.Get("Etag"))
351 })
352 }
353 }
354
355 func TestNewGzipLevelHandler(t *testing.T) {
356 handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
357 w.WriteHeader(http.StatusOK)
358 w.Write(testBody)
359 })
360
361 for lvl := gzip.StatelessCompression; lvl <= gzip.BestCompression; lvl++ {
362 t.Run(fmt.Sprint(lvl), func(t *testing.T) {
363 wrapper, err := NewWrapper(CompressionLevel(lvl))
364 assertNil(t, err)
365
366 req, _ := http.NewRequest("GET", "/whatever", nil)
367 req.Header.Set("Accept-Encoding", "gzip")
368 resp := httptest.NewRecorder()
369 wrapper(handler).ServeHTTP(resp, req)
370 res := resp.Result()
371
372 assertEqual(t, 200, res.StatusCode)
373 assertEqual(t, "gzip", res.Header.Get("Content-Encoding"))
374 assertEqual(t, "Accept-Encoding", res.Header.Get("Vary"))
375 got := gzipStrLevel(testBody, lvl)
376 if lvl != gzip.StatelessCompression {
377 assertEqual(t, got, resp.Body.Bytes())
378 }
379 t.Log(lvl, len(got))
380 })
381 }
382 }
383
384 func TestNewGzipLevelHandlerReturnsErrorForInvalidLevels(t *testing.T) {
385 var err error
386 _, err = NewWrapper(CompressionLevel(-42))
387 assertNotNil(t, err)
388
389 _, err = NewWrapper(CompressionLevel(42))
390 assertNotNil(t, err)
391 }
392
393 func TestMustNewGzipLevelHandlerWillPanic(t *testing.T) {
394 defer func() {
395 if r := recover(); r != nil {
396 t.Error("panic was called with", r)
397 }
398 }()
399
400 _ = GzipHandler(nil)
401 }
402
403 func TestGzipHandlerNoBody(t *testing.T) {
404 tests := []struct {
405 statusCode int
406 contentEncoding string
407 emptyBody bool
408 body []byte
409 }{
410 // Body must be empty.
411 {http.StatusNoContent, "", true, nil},
412 {http.StatusNotModified, "", true, nil},
413 // Body is going to get gzip'd no matter what.
414 {http.StatusOK, "", true, []byte{}},
415 {http.StatusOK, "gzip", false, []byte(testBody)},
416 }
417
418 for num, test := range tests {
419 t.Run(fmt.Sprintf("test-%d", num), func(t *testing.T) {
420 handler := GzipHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
421 w.WriteHeader(test.statusCode)
422 if test.body != nil {
423 w.Write(test.body)
424 }
425 }))
426
427 rec := httptest.NewRecorder()
428 req := httptest.NewRequest(http.MethodGet, "/", nil)
429 req.Header.Set("Accept-Encoding", "gzip")
430 handler.ServeHTTP(rec, req)
431
432 body, err := io.ReadAll(rec.Body)
433 if err != nil {
434 t.Fatalf("Unexpected error reading response body: %v", err)
435 }
436
437 header := rec.Header()
438 assertEqual(t, test.contentEncoding, header.Get("Content-Encoding"))
439 assertEqual(t, "Accept-Encoding", header.Get("Vary"))
440 if test.emptyBody {
441 assertEqual(t, 0, len(body))
442 } else {
443 assertNotEqual(t, 0, len(body))
444 assertNotEqual(t, test.body, body)
445 }
446 })
447
448 }
449 }
450
451 func TestGzipHandlerContentLength(t *testing.T) {
452 testBodyBytes := []byte(testBody)
453 tests := []struct {
454 bodyLen int
455 bodies [][]byte
456 emptyBody bool
457 }{
458 {len(testBody), [][]byte{testBodyBytes}, false},
459 // each of these writes is less than the DefaultMinSize
460 {len(testBody), [][]byte{testBodyBytes[:200], testBodyBytes[200:]}, false},
461 // without a defined Content-Length it should still gzip
462 {0, [][]byte{testBodyBytes[:200], testBodyBytes[200:]}, false},
463 // simulate a HEAD request with an empty write (to populate headers)
464 {len(testBody), [][]byte{nil}, true},
465 }
466
467 // httptest.NewRecorder doesn't give you access to the Content-Length
468 // header so instead, we create a server on a random port and make
469 // a request to that instead
470 ln, err := net.Listen("tcp", "localhost:")
471 if err != nil {
472 t.Fatalf("failed creating listen socket: %v", err)
473 }
474 defer ln.Close()
475 srv := &http.Server{
476 Handler: nil,
477 }
478 go srv.Serve(ln)
479
480 for num, test := range tests {
481 t.Run(fmt.Sprintf("test-%d", num), func(t *testing.T) {
482 srv.Handler = GzipHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
483 if test.bodyLen > 0 {
484 w.Header().Set("Content-Length", strconv.Itoa(test.bodyLen))
485 }
486 for _, b := range test.bodies {
487 w.Write(b)
488 }
489 }))
490 req := &http.Request{
491 Method: "GET",
492 URL: &url.URL{Path: "/", Scheme: "http", Host: ln.Addr().String()},
493 Header: make(http.Header),
494 Close: true,
495 }
496 req.Header.Set("Accept-Encoding", "gzip")
497 res, err := http.DefaultClient.Do(req)
498 if err != nil {
499 t.Fatalf("Unexpected error making http request in test iteration %d: %v", num, err)
500 }
501 defer res.Body.Close()
502
503 body, err := io.ReadAll(res.Body)
504 if err != nil {
505 t.Fatalf("Unexpected error reading response body in test iteration %d: %v", num, err)
506 }
507
508 l, err := strconv.Atoi(res.Header.Get("Content-Length"))
509 if err != nil {
510 t.Fatalf("Unexpected error parsing Content-Length in test iteration %d: %v", num, err)
511 }
512 if test.emptyBody {
513 assertEqual(t, 0, len(body))
514 assertEqual(t, 0, l)
515 } else {
516 assertEqual(t, len(body), l)
517 }
518 assertEqual(t, "gzip", res.Header.Get("Content-Encoding"))
519 assertNotEqual(t, test.bodyLen, l)
520 })
521 }
522 }
523
524 func TestGzipHandlerMinSizeMustBePositive(t *testing.T) {
525 _, err := NewWrapper(MinSize(-1))
526 assertNotNil(t, err)
527 }
528
529 func TestGzipHandlerMinSize(t *testing.T) {
530 responseLength := 0
531 b := []byte{'x'}
532
533 wrapper, _ := NewWrapper(MinSize(128))
534 handler := wrapper(http.HandlerFunc(
535 func(w http.ResponseWriter, r *http.Request) {
536 // Write responses one byte at a time to ensure that the flush
537 // mechanism, if used, is working properly.
538 for i := 0; i < responseLength; i++ {
539 n, err := w.Write(b)
540 assertEqual(t, 1, n)
541 assertNil(t, err)
542 }
543 },
544 ))
545
546 r, _ := http.NewRequest("GET", "/whatever", &bytes.Buffer{})
547 r.Header.Add("Accept-Encoding", "gzip")
548
549 // Short response is not compressed
550 responseLength = 127
551 w := httptest.NewRecorder()
552 handler.ServeHTTP(w, r)
553 if w.Result().Header.Get(contentEncoding) == "gzip" {
554 t.Error("Expected uncompressed response, got compressed")
555 }
556
557 // Long response is not compressed
558 responseLength = 128
559 w = httptest.NewRecorder()
560 handler.ServeHTTP(w, r)
561 if w.Result().Header.Get(contentEncoding) != "gzip" {
562 t.Error("Expected compressed response, got uncompressed")
563 }
564 }
565
566 type panicOnSecondWriteHeaderWriter struct {
567 http.ResponseWriter
568 headerWritten bool
569 }
570
571 func (w *panicOnSecondWriteHeaderWriter) WriteHeader(s int) {
572 if w.headerWritten {
573 panic("header already written")
574 }
575 w.headerWritten = true
576 w.ResponseWriter.WriteHeader(s)
577 }
578
579 func TestGzipHandlerDoubleWriteHeader(t *testing.T) {
580 handler := GzipHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
581 w.Header().Set("Content-Length", "15000")
582 // Specifically write the header here
583 w.WriteHeader(304)
584 // Ensure that after a Write the header isn't triggered again on close
585 w.Write(nil)
586 }))
587 wrapper := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
588 w = &panicOnSecondWriteHeaderWriter{
589 ResponseWriter: w,
590 }
591 handler.ServeHTTP(w, r)
592 })
593
594 rec := httptest.NewRecorder()
595 // TODO: in Go1.7 httptest.NewRequest was introduced this should be used
596 // once 1.6 is not longer supported.
597 req := &http.Request{
598 Method: "GET",
599 URL: &url.URL{Path: "/"},
600 Proto: "HTTP/1.1",
601 ProtoMinor: 1,
602 RemoteAddr: "192.0.2.1:1234",
603 Header: make(http.Header),
604 }
605 req.Header.Set("Accept-Encoding", "gzip")
606 wrapper.ServeHTTP(rec, req)
607 body, err := io.ReadAll(rec.Body)
608 if err != nil {
609 t.Fatalf("Unexpected error reading response body: %v", err)
610 }
611 assertEqual(t, 0, len(body))
612 header := rec.Header()
613 assertEqual(t, "gzip", header.Get("Content-Encoding"))
614 assertEqual(t, "Accept-Encoding", header.Get("Vary"))
615 assertEqual(t, 304, rec.Code)
616 }
617
618 func TestStatusCodes(t *testing.T) {
619 handler := GzipHandler(http.NotFoundHandler())
620 r := httptest.NewRequest("GET", "/", nil)
621 r.Header.Set("Accept-Encoding", "gzip")
622 w := httptest.NewRecorder()
623 handler.ServeHTTP(w, r)
624
625 result := w.Result()
626 if result.StatusCode != 404 {
627 t.Errorf("StatusCode should have been 404 but was %d", result.StatusCode)
628 }
629 }
630
631 func TestFlushBeforeWrite(t *testing.T) {
632 b := []byte(testBody)
633 handler := GzipHandler(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
634 rw.WriteHeader(http.StatusNotFound)
635 rw.(http.Flusher).Flush()
636 rw.Write(b)
637 }))
638 r := httptest.NewRequest(http.MethodGet, "/", nil)
639 r.Header.Set("Accept-Encoding", "gzip")
640 w := httptest.NewRecorder()
641 handler.ServeHTTP(w, r)
642
643 res := w.Result()
644 assertEqual(t, http.StatusNotFound, res.StatusCode)
645 assertEqual(t, "gzip", res.Header.Get("Content-Encoding"))
646 assertNotEqual(t, b, w.Body.Bytes())
647 }
648
649 func TestFlushAfterWrite(t *testing.T) {
650 b := testBody[:1000]
651 handler := GzipHandler(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
652 rw.WriteHeader(http.StatusOK)
653 rw.Write(b[0:1])
654 rw.(http.Flusher).Flush()
655 for i := range b[1:] {
656 rw.Write(b[i+1 : i+2])
657 }
658 }))
659 r := httptest.NewRequest(http.MethodGet, "/", nil)
660 r.Header.Set("Accept-Encoding", "gzip")
661 w := httptest.NewRecorder()
662 handler.ServeHTTP(w, r)
663
664 res := w.Result()
665 assertEqual(t, http.StatusOK, res.StatusCode)
666 assertEqual(t, "gzip", res.Header.Get("Content-Encoding"))
667 gr, err := gzip.NewReader(w.Body)
668 assertNil(t, err)
669 got, err := io.ReadAll(gr)
670 assertNil(t, err)
671 assertEqual(t, b, got)
672 }
673
674 func TestFlushAfterWrite2(t *testing.T) {
675 b := testBody[:1050]
676 handler := GzipHandler(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
677 for i := range b {
678 rw.Write(b[i : i+1])
679 }
680 rw.(http.Flusher).Flush()
681 }))
682 r := httptest.NewRequest(http.MethodGet, "/", nil)
683 r.Header.Set("Accept-Encoding", "gzip")
684 w := httptest.NewRecorder()
685 handler.ServeHTTP(w, r)
686
687 res := w.Result()
688 assertEqual(t, http.StatusOK, res.StatusCode)
689 assertEqual(t, "gzip", res.Header.Get("Content-Encoding"))
690 gr, err := gzip.NewReader(w.Body)
691 assertNil(t, err)
692 got, err := io.ReadAll(gr)
693 assertNil(t, err)
694 assertEqual(t, b, got)
695 }
696
697 func TestFlushAfterWrite3(t *testing.T) {
698 b := []byte(nil)
699 gz, err := NewWrapper(MinSize(1000), CompressionLevel(gzip.BestSpeed))
700 if err != nil {
701 // Static params, so this is very unlikely.
702 t.Fatal(err, "Unable to initialize server")
703 }
704 handler := gz(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
705 rw.WriteHeader(http.StatusOK)
706 // rw.Write(nil)
707 rw.(http.Flusher).Flush()
708 }))
709 r := httptest.NewRequest(http.MethodGet, "/", nil)
710 r.Header.Set("Accept-Encoding", "gzip")
711 w := httptest.NewRecorder()
712 handler.ServeHTTP(w, r)
713
714 res := w.Result()
715 assertEqual(t, http.StatusOK, res.StatusCode)
716 assertEqual(t, "", res.Header.Get("Content-Encoding"))
717 assertEqual(t, b, w.Body.Bytes())
718 }
719
720 func TestImplementCloseNotifier(t *testing.T) {
721 request := httptest.NewRequest(http.MethodGet, "/", nil)
722 request.Header.Set(acceptEncoding, "gzip")
723 GzipHandler(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
724 _, ok := rw.(http.CloseNotifier)
725 // response writer must implement http.CloseNotifier
726 assertEqual(t, true, ok)
727 })).ServeHTTP(&mockRWCloseNotify{}, request)
728 }
729
730 func TestImplementFlusherAndCloseNotifier(t *testing.T) {
731 request := httptest.NewRequest(http.MethodGet, "/", nil)
732 request.Header.Set(acceptEncoding, "gzip")
733 GzipHandler(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
734 _, okCloseNotifier := rw.(http.CloseNotifier)
735 // response writer must implement http.CloseNotifier
736 assertEqual(t, true, okCloseNotifier)
737 _, okFlusher := rw.(http.Flusher)
738 // "response writer must implement http.Flusher"
739 assertEqual(t, true, okFlusher)
740 })).ServeHTTP(&mockRWCloseNotify{}, request)
741 }
742
743 func TestNotImplementCloseNotifier(t *testing.T) {
744 request := httptest.NewRequest(http.MethodGet, "/", nil)
745 request.Header.Set(acceptEncoding, "gzip")
746 GzipHandler(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
747 _, ok := rw.(http.CloseNotifier)
748 // response writer must not implement http.CloseNotifier
749 assertEqual(t, false, ok)
750 })).ServeHTTP(httptest.NewRecorder(), request)
751 }
752
753 type mockRWCloseNotify struct{}
754
755 func (m *mockRWCloseNotify) CloseNotify() <-chan bool {
756 panic("implement me")
757 }
758
759 func (m *mockRWCloseNotify) Header() http.Header {
760 return http.Header{}
761 }
762
763 func (m *mockRWCloseNotify) Write([]byte) (int, error) {
764 panic("implement me")
765 }
766
767 func (m *mockRWCloseNotify) WriteHeader(int) {
768 panic("implement me")
769 }
770
771 func TestIgnoreSubsequentWriteHeader(t *testing.T) {
772 handler := GzipHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
773 w.WriteHeader(500)
774 w.WriteHeader(404)
775 }))
776 r := httptest.NewRequest("GET", "/", nil)
777 r.Header.Set("Accept-Encoding", "gzip")
778 w := httptest.NewRecorder()
779 handler.ServeHTTP(w, r)
780
781 result := w.Result()
782 if result.StatusCode != 500 {
783 t.Errorf("StatusCode should have been 500 but was %d", result.StatusCode)
784 }
785 }
786
787 func TestDontWriteWhenNotWrittenTo(t *testing.T) {
788 // When using gzip as middleware without ANY writes in the handler,
789 // ensure the gzip middleware doesn't touch the actual ResponseWriter
790 // either.
791
792 handler0 := GzipHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
793 }))
794
795 handler1 := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
796 handler0.ServeHTTP(w, r)
797 w.WriteHeader(404) // this only works if gzip didn't do a WriteHeader(200)
798 })
799
800 r := httptest.NewRequest("GET", "/", nil)
801 r.Header.Set("Accept-Encoding", "gzip")
802 w := httptest.NewRecorder()
803 handler1.ServeHTTP(w, r)
804
805 result := w.Result()
806 if result.StatusCode != 404 {
807 t.Errorf("StatusCode should have been 404 but was %d", result.StatusCode)
808 }
809 }
810
811 var contentTypeTests = []struct {
812 name string
813 contentType string
814 acceptedContentTypes []string
815 expectedGzip bool
816 }{
817 {
818 name: "Always gzip when content types are empty",
819 contentType: "",
820 acceptedContentTypes: []string{},
821 expectedGzip: true,
822 },
823 {
824 name: "MIME match",
825 contentType: "application/json",
826 acceptedContentTypes: []string{"application/json"},
827 expectedGzip: true,
828 },
829 {
830 name: "MIME no match",
831 contentType: "text/xml",
832 acceptedContentTypes: []string{"application/json"},
833 expectedGzip: false,
834 },
835 {
836 name: "MIME match with no other directive ignores non-MIME directives",
837 contentType: "application/json; charset=utf-8",
838 acceptedContentTypes: []string{"application/json"},
839 expectedGzip: true,
840 },
841 {
842 name: "MIME match with other directives requires all directives be equal, different charset",
843 contentType: "application/json; charset=ascii",
844 acceptedContentTypes: []string{"application/json; charset=utf-8"},
845 expectedGzip: false,
846 },
847 {
848 name: "MIME match with other directives requires all directives be equal, same charset",
849 contentType: "application/json; charset=utf-8",
850 acceptedContentTypes: []string{"application/json; charset=utf-8"},
851 expectedGzip: true,
852 },
853 {
854 name: "MIME match with other directives requires all directives be equal, missing charset",
855 contentType: "application/json",
856 acceptedContentTypes: []string{"application/json; charset=ascii"},
857 expectedGzip: false,
858 },
859 {
860 name: "MIME match case insensitive",
861 contentType: "Application/Json",
862 acceptedContentTypes: []string{"application/json"},
863 expectedGzip: true,
864 },
865 {
866 name: "MIME match ignore whitespace",
867 contentType: "application/json;charset=utf-8",
868 acceptedContentTypes: []string{"application/json; charset=utf-8"},
869 expectedGzip: true,
870 },
871 }
872
873 func TestContentTypes(t *testing.T) {
874 for _, tt := range contentTypeTests {
875 t.Run(tt.name, func(t *testing.T) {
876 handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
877 w.WriteHeader(http.StatusOK)
878 w.Header().Set("Content-Type", tt.contentType)
879 w.Write(testBody)
880 })
881
882 wrapper, err := NewWrapper(ContentTypes(tt.acceptedContentTypes))
883 assertNil(t, err)
884
885 req, _ := http.NewRequest("GET", "/whatever", nil)
886 req.Header.Set("Accept-Encoding", "gzip")
887 resp := httptest.NewRecorder()
888 wrapper(handler).ServeHTTP(resp, req)
889 res := resp.Result()
890
891 assertEqual(t, 200, res.StatusCode)
892 if tt.expectedGzip {
893 assertEqual(t, "gzip", res.Header.Get("Content-Encoding"))
894 } else {
895 assertNotEqual(t, "gzip", res.Header.Get("Content-Encoding"))
896 }
897 })
898 t.Run("not-"+tt.name, func(t *testing.T) {
899 handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
900 w.WriteHeader(http.StatusOK)
901 w.Header().Set("Content-Type", tt.contentType)
902 w.Write(testBody)
903 })
904
905 wrapper, err := NewWrapper(ExceptContentTypes(tt.acceptedContentTypes))
906 assertNil(t, err)
907
908 req, _ := http.NewRequest("GET", "/whatever", nil)
909 req.Header.Set("Accept-Encoding", "gzip")
910 resp := httptest.NewRecorder()
911 wrapper(handler).ServeHTTP(resp, req)
912 res := resp.Result()
913
914 assertEqual(t, 200, res.StatusCode)
915 if !tt.expectedGzip {
916 assertEqual(t, "gzip", res.Header.Get("Content-Encoding"))
917 } else {
918 assertNotEqual(t, "gzip", res.Header.Get("Content-Encoding"))
919 }
920 })
921 t.Run("disable-"+tt.name, func(t *testing.T) {
922 handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
923 w.Header().Set("Content-Type", tt.contentType)
924 w.Header().Set(HeaderNoCompression, "plz")
925 w.WriteHeader(http.StatusOK)
926 w.Write(testBody)
927 })
928
929 wrapper, err := NewWrapper(ContentTypes(tt.acceptedContentTypes))
930 assertNil(t, err)
931
932 req, _ := http.NewRequest("GET", "/whatever", nil)
933 req.Header.Set("Accept-Encoding", "gzip")
934 resp := httptest.NewRecorder()
935 wrapper(handler).ServeHTTP(resp, req)
936 res := resp.Result()
937
938 assertEqual(t, 200, res.StatusCode)
939 assertNotEqual(t, "gzip", res.Header.Get("Content-Encoding"))
940 _, ok := res.Header[HeaderNoCompression]
941 assertEqual(t, false, ok)
942 })
943 t.Run("head-req"+tt.name, func(t *testing.T) {
944 handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
945 w.Header().Set("Content-Type", tt.contentType)
946 w.Header().Set(HeaderNoCompression, "plz")
947 w.WriteHeader(http.StatusOK)
948 })
949
950 wrapper, err := NewWrapper(ContentTypes(tt.acceptedContentTypes))
951 assertNil(t, err)
952
953 req, _ := http.NewRequest("HEAD", "/whatever", nil)
954 req.Header.Set("Accept-Encoding", "gzip")
955 resp := httptest.NewRecorder()
956 wrapper(handler).ServeHTTP(resp, req)
957 res := resp.Result()
958
959 assertEqual(t, 200, res.StatusCode)
960 assertNotEqual(t, "gzip", res.Header.Get("Content-Encoding"))
961 _, ok := res.Header[HeaderNoCompression]
962 assertEqual(t, false, ok)
963 })
964 t.Run("head-req-no-ok"+tt.name, func(t *testing.T) {
965 handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
966 w.Header().Set("Content-Type", tt.contentType)
967 w.Header().Set(HeaderNoCompression, "plz")
968 })
969
970 wrapper, err := NewWrapper(ContentTypes(tt.acceptedContentTypes))
971 assertNil(t, err)
972
973 req, _ := http.NewRequest("HEAD", "/whatever", nil)
974 req.Header.Set("Accept-Encoding", "gzip")
975 resp := httptest.NewRecorder()
976 wrapper(handler).ServeHTTP(resp, req)
977 res := resp.Result()
978
979 assertEqual(t, 200, res.StatusCode)
980 assertNotEqual(t, "gzip", res.Header.Get("Content-Encoding"))
981 _, ok := res.Header[HeaderNoCompression]
982 assertEqual(t, false, ok)
983 })
984 t.Run("req-no-ok-write"+tt.name, func(t *testing.T) {
985 handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
986 w.Header().Set("Content-Type", tt.contentType)
987 w.Header().Set(HeaderNoCompression, "plz")
988 w.Write(testBody)
989 })
990
991 wrapper, err := NewWrapper(ContentTypes(tt.acceptedContentTypes))
992 assertNil(t, err)
993
994 req, _ := http.NewRequest("GET", "/whatever", nil)
995 req.Header.Set("Accept-Encoding", "")
996 resp := httptest.NewRecorder()
997 wrapper(handler).ServeHTTP(resp, req)
998 res := resp.Result()
999
1000 assertEqual(t, 200, res.StatusCode)
1001 assertNotEqual(t, "gzip", res.Header.Get("Content-Encoding"))
1002 _, ok := res.Header[HeaderNoCompression]
1003 assertEqual(t, false, ok)
1004 })
1005 }
1006 }
1007
1008 func TestFlush(t *testing.T) {
1009 for _, tt := range contentTypeTests {
1010 t.Run(tt.name, func(t *testing.T) {
1011 handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
1012 w.WriteHeader(http.StatusOK)
1013 w.Header().Set("Content-Type", tt.contentType)
1014 tb := testBody
1015 for len(tb) > 0 {
1016 // Write 100 bytes per run
1017 // Detection should not be affected (we send 100 bytes)
1018 toWrite := min(100, len(tb))
1019 _, err := w.Write(tb[:toWrite])
1020 if err != nil {
1021 t.Fatal(err)
1022 }
1023 // Flush between each write
1024 w.(http.Flusher).Flush()
1025 tb = tb[toWrite:]
1026 }
1027 })
1028
1029 wrapper, err := NewWrapper(ContentTypes(tt.acceptedContentTypes))
1030 assertNil(t, err)
1031
1032 req, _ := http.NewRequest("GET", "/whatever", nil)
1033 req.Header.Set("Accept-Encoding", "gzip")
1034 // This doesn't allow checking flushes, but we validate if content is correct.
1035 resp := httptest.NewRecorder()
1036 wrapper(handler).ServeHTTP(resp, req)
1037 res := resp.Result()
1038
1039 assertEqual(t, 200, res.StatusCode)
1040 if tt.expectedGzip {
1041 assertEqual(t, "gzip", res.Header.Get("Content-Encoding"))
1042 zr, err := gzip.NewReader(resp.Body)
1043 assertNil(t, err)
1044 got, err := io.ReadAll(zr)
1045 assertNil(t, err)
1046 assertEqual(t, testBody, got)
1047
1048 } else {
1049 assertNotEqual(t, "gzip", res.Header.Get("Content-Encoding"))
1050 got, err := io.ReadAll(resp.Body)
1051 assertNil(t, err)
1052 assertEqual(t, testBody, got)
1053 }
1054 })
1055 }
1056 }
1057
1058 func TestRandomJitter(t *testing.T) {
1059 r := httptest.NewRequest("GET", "/", nil)
1060 r.Header.Set("Accept-Encoding", "gzip")
1061
1062 // 4KB input, incompressible to avoid compression variations.
1063 rng := rand.New(rand.NewSource(0))
1064 payload := make([]byte, 4096)
1065 _, err := io.ReadFull(rng, payload)
1066 if err != nil {
1067 t.Fatal(err)
1068 }
1069
1070 wrapper, err := NewWrapper(RandomJitter(256, 1024, false), MinSize(10))
1071 if err != nil {
1072 t.Fatal(err)
1073 }
1074 writePayload := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
1075 w.Write(payload)
1076 })
1077 referenceHandler := GzipHandler(writePayload)
1078 w := httptest.NewRecorder()
1079 referenceHandler.ServeHTTP(w, r)
1080 result := w.Result()
1081 refBody, err := io.ReadAll(result.Body)
1082 if err != nil {
1083 t.Fatal(err)
1084 }
1085 t.Logf("Unmodified length: %d", len(refBody))
1086
1087 handler := wrapper(writePayload)
1088 w = httptest.NewRecorder()
1089 handler.ServeHTTP(w, r)
1090
1091 result = w.Result()
1092 b, err := io.ReadAll(result.Body)
1093 if err != nil {
1094 t.Fatal(err)
1095 }
1096
1097 if len(refBody) == len(b) {
1098 t.Fatal("padding was not applied")
1099 }
1100
1101 if err != nil {
1102 t.Fatal(err)
1103 }
1104 changed := false
1105 for i := range 10 {
1106 w = httptest.NewRecorder()
1107 handler.ServeHTTP(w, r)
1108 result = w.Result()
1109 b2, err := io.ReadAll(result.Body)
1110 if err != nil {
1111 t.Fatal(err)
1112 }
1113 changed = changed || len(b2) != len(b)
1114 t.Logf("attempt %d length: %d. padding: %d.", i, len(b2), len(b2)-len(refBody))
1115 if len(b2) <= len(refBody) {
1116 t.Errorf("no padding applied,")
1117 }
1118 if i == 0 && changed {
1119 t.Error("length changed without payload change", len(b), "->", len(b2))
1120 }
1121 // Mutate...
1122 payload[0]++
1123 b = b2
1124 }
1125 if !changed {
1126 t.Errorf("no change after 9 attempts")
1127 }
1128
1129 // Write one byte at the time to test buffer flushing.
1130 handler = wrapper(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
1131 for i := range payload {
1132 w.Write([]byte{payload[i]})
1133 }
1134 }))
1135
1136 for i := range 10 {
1137 w = httptest.NewRecorder()
1138 handler.ServeHTTP(w, r)
1139 result = w.Result()
1140 b2, err := io.ReadAll(result.Body)
1141 if err != nil {
1142 t.Fatal(err)
1143 }
1144
1145 t.Logf("attempt %d length: %d. padding: %d.", i, len(b2), len(b2)-len(refBody))
1146 if len(b2) <= len(refBody) {
1147 t.Errorf("no padding applied,")
1148 }
1149 if i > 0 && len(b2) != len(b) {
1150 t.Error("length changed without payload change", len(b), "->", len(b2))
1151 }
1152 // Mutate, buf after the buffer...
1153 payload[2048]++
1154 b = b2
1155 }
1156
1157 // Write less than buffer
1158 handler = wrapper(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
1159 w.Write(payload[:512])
1160 }))
1161 changed = false
1162 for i := range 10 {
1163 w = httptest.NewRecorder()
1164 handler.ServeHTTP(w, r)
1165 result = w.Result()
1166 b2, err := io.ReadAll(result.Body)
1167 if err != nil {
1168 t.Fatal(err)
1169 }
1170 if i > 0 {
1171 changed = changed || len(b2) != len(b)
1172 }
1173 t.Logf("attempt %d length: %d. padding: %d.", i, len(b2), len(b2)-512)
1174 if len(b2) <= 512 {
1175 t.Errorf("no padding applied,")
1176 }
1177 // Mutate...
1178 payload[500]++
1179 b = b2
1180 }
1181 if !changed {
1182 t.Errorf("no change after 9 attempts")
1183 }
1184
1185 // Write less than buffer, with flush in between.
1186 // Checksum should be of all before flush.
1187 handler = wrapper(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
1188 w.Write(payload[:256])
1189 w.(http.Flusher).Flush()
1190 w.Write(payload[256:512])
1191 }))
1192
1193 changed = false
1194 for i := range 10 {
1195 w = httptest.NewRecorder()
1196 handler.ServeHTTP(w, r)
1197 result = w.Result()
1198 b2, err := io.ReadAll(result.Body)
1199 if err != nil {
1200 t.Fatal(err)
1201 }
1202 if i > 0 {
1203 changed = changed || len(b2) != len(b)
1204 }
1205 t.Logf("attempt %d length: %d. padding: %d.", i, len(b2), len(b2)-512)
1206 if len(b2) <= 512 {
1207 t.Errorf("no padding applied,")
1208 }
1209 // Mutate...
1210 payload[200]++
1211 b = b2
1212 }
1213 if !changed {
1214 t.Errorf("no change after 9 attempts")
1215 }
1216
1217 // Mutate *after* the flush.
1218 // Should no longer affect length.
1219 for i := range 10 {
1220 w = httptest.NewRecorder()
1221 handler.ServeHTTP(w, r)
1222 result = w.Result()
1223 b2, err := io.ReadAll(result.Body)
1224 if err != nil {
1225 t.Fatal(err)
1226 }
1227 if i > 0 {
1228 changed = len(b2) != len(b)
1229 if changed {
1230 t.Errorf("mutating after flush seems to have affected output")
1231 }
1232 }
1233 t.Logf("attempt %d length: %d. padding: %d.", i, len(b2), len(b2)-512)
1234 if len(b2) <= 512 {
1235 t.Errorf("no padding applied,")
1236 }
1237 // Mutate...
1238 payload[400]++
1239 b = b2
1240 }
1241
1242 // Test non-content aware jitter
1243 wrapper, err = NewWrapper(RandomJitter(256, -1, false), MinSize(10))
1244 if err != nil {
1245 t.Fatal(err)
1246 }
1247 handler = wrapper(writePayload)
1248 changed = false
1249 for i := range 10 {
1250 w = httptest.NewRecorder()
1251 handler.ServeHTTP(w, r)
1252 result = w.Result()
1253 b2, err := io.ReadAll(result.Body)
1254 if err != nil {
1255 t.Fatal(err)
1256 }
1257 if i > 0 {
1258 changed = changed || len(b2) != len(b)
1259 }
1260 t.Logf("attempt %d length: %d. padding: %d.", i, len(b2), len(b2)-len(refBody))
1261 if len(b2) <= len(refBody) {
1262 t.Errorf("no padding applied,")
1263 }
1264
1265 // Do not mutate...
1266 // Update last payload.
1267 b = b2
1268 }
1269 if !changed {
1270 t.Errorf("no change after 9 attempts")
1271 }
1272 }
1273
1274 // TestRandomJitterBufferWriteSizeIndependent verifies that when jitterBuffer is
1275 // smaller than the internal write buffer (wantBuf = max(minSize, 512)), the
1276 // padding seed only hashes the first jitterBuffer bytes — not the entire
1277 // internal buffer — so output does not depend on Write() chunking (#1191).
1278 func TestRandomJitterBufferWriteSizeIndependent(t *testing.T) {
1279 r := httptest.NewRequest("GET", "/", nil)
1280 r.Header.Set("Accept-Encoding", "gzip")
1281
1282 rng := rand.New(rand.NewSource(1))
1283 payload := make([]byte, 4096)
1284 if _, err := io.ReadFull(rng, payload); err != nil {
1285 t.Fatal(err)
1286 }
1287
1288 // jitterBuffer=64 << wantBuf (max(minSize,512)=512). Before the fix, a
1289 // single large Write hashed all 512 buffered bytes while byte-at-a-time
1290 // Writes hashed only 64, producing different padding.
1291 const jitterBuf = 64
1292 for _, paranoid := range []bool{false, true} {
1293 t.Run(fmt.Sprintf("paranoid=%v", paranoid), func(t *testing.T) {
1294 wrapper, err := NewWrapper(RandomJitter(256, jitterBuf, paranoid), MinSize(10))
1295 if err != nil {
1296 t.Fatal(err)
1297 }
1298
1299 serve := func(write func(http.ResponseWriter)) int {
1300 h := wrapper(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
1301 write(w)
1302 }))
1303 rec := httptest.NewRecorder()
1304 h.ServeHTTP(rec, r)
1305 body, err := io.ReadAll(rec.Result().Body)
1306 if err != nil {
1307 t.Fatal(err)
1308 }
1309 return len(body)
1310 }
1311
1312 oneShot := serve(func(w http.ResponseWriter) {
1313 w.Write(payload)
1314 })
1315 chunked := serve(func(w http.ResponseWriter) {
1316 for i := range payload {
1317 w.Write([]byte{payload[i]})
1318 }
1319 })
1320 // Large first chunk past jitterBuffer, then rest.
1321 chunkedLarge := serve(func(w http.ResponseWriter) {
1322 w.Write(payload[:1024])
1323 w.Write(payload[1024:])
1324 })
1325
1326 if oneShot != chunked {
1327 t.Errorf("one-shot Write len %d != byte-at-a-time len %d", oneShot, chunked)
1328 }
1329 if oneShot != chunkedLarge {
1330 t.Errorf("one-shot Write len %d != large-then-rest len %d", oneShot, chunkedLarge)
1331 }
1332
1333 // Mutating only past jitterBuffer must not change padding length.
1334 payload2 := bytes.Clone(payload)
1335 payload2[jitterBuf]++
1336 payload2[jitterBuf+100]++
1337 mutated := serve(func(w http.ResponseWriter) {
1338 w.Write(payload2)
1339 })
1340 if mutated != oneShot {
1341 t.Errorf("mutating after jitterBuffer changed length: got %d, want %d", mutated, oneShot)
1342 }
1343
1344 // Mutating within jitterBuffer should change padding (usually).
1345 payload3 := bytes.Clone(payload)
1346 changed := false
1347 for i := range jitterBuf {
1348 payload3[i]++
1349 mutIn := serve(func(w http.ResponseWriter) {
1350 w.Write(payload3)
1351 })
1352 if mutIn != oneShot {
1353 changed = true
1354 break
1355 }
1356 }
1357 if !changed {
1358 t.Error("mutating within jitterBuffer never changed padding length")
1359 }
1360 })
1361 }
1362 }
1363
1364 func TestRandomJitterParanoid(t *testing.T) {
1365 r := httptest.NewRequest("GET", "/", nil)
1366 r.Header.Set("Accept-Encoding", "gzip")
1367
1368 // 4KB input, incompressible to avoid compression variations.
1369 rng := rand.New(rand.NewSource(0))
1370 payload := make([]byte, 4096)
1371 _, err := io.ReadFull(rng, payload)
1372 if err != nil {
1373 t.Fatal(err)
1374 }
1375
1376 wrapper, err := NewWrapper(RandomJitter(256, 1024, true), MinSize(10))
1377 if err != nil {
1378 t.Fatal(err)
1379 }
1380 writePayload := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
1381 w.Write(payload)
1382 })
1383 referenceHandler := GzipHandler(writePayload)
1384 w := httptest.NewRecorder()
1385 referenceHandler.ServeHTTP(w, r)
1386 result := w.Result()
1387 refBody, err := io.ReadAll(result.Body)
1388 if err != nil {
1389 t.Fatal(err)
1390 }
1391 t.Logf("Unmodified length: %d", len(refBody))
1392
1393 handler := wrapper(writePayload)
1394 w = httptest.NewRecorder()
1395 handler.ServeHTTP(w, r)
1396
1397 result = w.Result()
1398 b, err := io.ReadAll(result.Body)
1399 if err != nil {
1400 t.Fatal(err)
1401 }
1402
1403 if len(refBody) == len(b) {
1404 t.Fatal("padding was not applied")
1405 }
1406
1407 if err != nil {
1408 t.Fatal(err)
1409 }
1410 changed := false
1411 for i := range 10 {
1412 w = httptest.NewRecorder()
1413 handler.ServeHTTP(w, r)
1414 result = w.Result()
1415 b2, err := io.ReadAll(result.Body)
1416 if err != nil {
1417 t.Fatal(err)
1418 }
1419 changed = changed || len(b2) != len(b)
1420 t.Logf("attempt %d length: %d. padding: %d.", i, len(b2), len(b2)-len(refBody))
1421 if len(b2) <= len(refBody) {
1422 t.Errorf("no padding applied,")
1423 }
1424 if i == 0 && changed {
1425 t.Error("length changed without payload change", len(b), "->", len(b2))
1426 }
1427 // Mutate...
1428 payload[0]++
1429 b = b2
1430 }
1431 if !changed {
1432 t.Errorf("no change after 9 attempts")
1433 }
1434
1435 // Write one byte at the time to test buffer flushing.
1436 handler = wrapper(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
1437 for i := range payload {
1438 w.Write([]byte{payload[i]})
1439 }
1440 }))
1441
1442 for i := range 10 {
1443 w = httptest.NewRecorder()
1444 handler.ServeHTTP(w, r)
1445 result = w.Result()
1446 b2, err := io.ReadAll(result.Body)
1447 if err != nil {
1448 t.Fatal(err)
1449 }
1450
1451 t.Logf("attempt %d length: %d. padding: %d.", i, len(b2), len(b2)-len(refBody))
1452 if len(b2) <= len(refBody) {
1453 t.Errorf("no padding applied,")
1454 }
1455 if i > 0 && len(b2) != len(b) {
1456 t.Error("length changed without payload change", len(b), "->", len(b2))
1457 }
1458 // Mutate, buf after the buffer...
1459 payload[2048]++
1460 b = b2
1461 }
1462
1463 // Write less than buffer
1464 handler = wrapper(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
1465 w.Write(payload[:512])
1466 }))
1467 changed = false
1468 for i := range 10 {
1469 w = httptest.NewRecorder()
1470 handler.ServeHTTP(w, r)
1471 result = w.Result()
1472 b2, err := io.ReadAll(result.Body)
1473 if err != nil {
1474 t.Fatal(err)
1475 }
1476 if i > 0 {
1477 changed = changed || len(b2) != len(b)
1478 }
1479 t.Logf("attempt %d length: %d. padding: %d.", i, len(b2), len(b2)-512)
1480 if len(b2) <= 512 {
1481 t.Errorf("no padding applied,")
1482 }
1483 // Mutate...
1484 payload[500]++
1485 b = b2
1486 }
1487 if !changed {
1488 t.Errorf("no change after 9 attempts")
1489 }
1490
1491 // Write less than buffer, with flush in between.
1492 // Checksum should be of all before flush.
1493 handler = wrapper(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
1494 w.Write(payload[:256])
1495 w.(http.Flusher).Flush()
1496 w.Write(payload[256:512])
1497 }))
1498
1499 changed = false
1500 for i := range 10 {
1501 w = httptest.NewRecorder()
1502 handler.ServeHTTP(w, r)
1503 result = w.Result()
1504 b2, err := io.ReadAll(result.Body)
1505 if err != nil {
1506 t.Fatal(err)
1507 }
1508 if i > 0 {
1509 changed = changed || len(b2) != len(b)
1510 }
1511 t.Logf("attempt %d length: %d. padding: %d.", i, len(b2), len(b2)-512)
1512 if len(b2) <= 512 {
1513 t.Errorf("no padding applied,")
1514 }
1515 // Mutate...
1516 payload[200]++
1517 b = b2
1518 }
1519 if !changed {
1520 t.Errorf("no change after 9 attempts")
1521 }
1522
1523 // Mutate *after* the flush.
1524 // Should no longer affect length.
1525 for i := range 10 {
1526 w = httptest.NewRecorder()
1527 handler.ServeHTTP(w, r)
1528 result = w.Result()
1529 b2, err := io.ReadAll(result.Body)
1530 if err != nil {
1531 t.Fatal(err)
1532 }
1533 if i > 0 {
1534 changed = len(b2) != len(b)
1535 if changed {
1536 t.Errorf("mutating after flush seems to have affected output")
1537 }
1538 }
1539 t.Logf("attempt %d length: %d. padding: %d.", i, len(b2), len(b2)-512)
1540 if len(b2) <= 512 {
1541 t.Errorf("no padding applied,")
1542 }
1543 // Mutate...
1544 payload[400]++
1545 b = b2
1546 }
1547
1548 // Test non-content aware jitter
1549 wrapper, err = NewWrapper(RandomJitter(256, -1, true), MinSize(10))
1550 if err != nil {
1551 t.Fatal(err)
1552 }
1553 handler = wrapper(writePayload)
1554 changed = false
1555 for i := range 10 {
1556 w = httptest.NewRecorder()
1557 handler.ServeHTTP(w, r)
1558 result = w.Result()
1559 b2, err := io.ReadAll(result.Body)
1560 if err != nil {
1561 t.Fatal(err)
1562 }
1563 if i > 0 {
1564 changed = changed || len(b2) != len(b)
1565 }
1566 t.Logf("attempt %d length: %d. padding: %d.", i, len(b2), len(b2)-len(refBody))
1567 if len(b2) <= len(refBody) {
1568 t.Errorf("no padding applied,")
1569 }
1570
1571 // Do not mutate...
1572 // Update last payload.
1573 b = b2
1574 }
1575 if !changed {
1576 t.Errorf("no change after 9 attempts")
1577 }
1578 }
1579
1580 var contentTypeTest2 = []struct {
1581 name string
1582 contentType string
1583 expectedGzip bool
1584 }{
1585 {
1586 name: "Always gzip when content types are empty",
1587 contentType: "",
1588 expectedGzip: true,
1589 },
1590 {
1591 name: "MIME match",
1592 contentType: "application/json",
1593 expectedGzip: true,
1594 },
1595 {
1596 name: "MIME no match",
1597 contentType: "text/xml",
1598 expectedGzip: true,
1599 },
1600
1601 {
1602 name: "MIME match case insensitive",
1603 contentType: "Video/Something",
1604 expectedGzip: false,
1605 },
1606 {
1607 name: "MIME match case insensitive",
1608 contentType: "audio/Something",
1609 expectedGzip: false,
1610 },
1611 {
1612 name: "MIME match ignore whitespace",
1613 contentType: " video/mp4",
1614 expectedGzip: false,
1615 },
1616 {
1617 name: "without prefix..",
1618 contentType: "avideo/mp4",
1619 expectedGzip: true,
1620 },
1621 {
1622 name: "application/zip",
1623 contentType: "application/zip;lalala",
1624 expectedGzip: false,
1625 },
1626 {
1627 name: "x-zip-compressed",
1628 contentType: "application/x-zip-compressed",
1629 expectedGzip: false,
1630 },
1631 {
1632 name: "application/x-gzip",
1633 contentType: "application/x-gzip",
1634 expectedGzip: false,
1635 },
1636 }
1637
1638 func TestDefaultContentTypes(t *testing.T) {
1639 for _, tt := range contentTypeTest2 {
1640 t.Run(tt.name, func(t *testing.T) {
1641 handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
1642 w.WriteHeader(http.StatusOK)
1643 w.Header().Set("Content-Type", tt.contentType)
1644 w.Write(testBody)
1645 })
1646
1647 wrapper, err := NewWrapper()
1648 assertNil(t, err)
1649
1650 req, _ := http.NewRequest("GET", "/whatever", nil)
1651 req.Header.Set("Accept-Encoding", "gzip")
1652 resp := httptest.NewRecorder()
1653 wrapper(handler).ServeHTTP(resp, req)
1654 res := resp.Result()
1655
1656 assertEqual(t, 200, res.StatusCode)
1657 if tt.expectedGzip {
1658 assertEqual(t, "gzip", res.Header.Get("Content-Encoding"))
1659 } else {
1660 assertNotEqual(t, "gzip", res.Header.Get("Content-Encoding"))
1661 }
1662 })
1663 }
1664 }
1665
1666 var sniffTests = []struct {
1667 desc string
1668 data []byte
1669 contentType string
1670 }{
1671 // Some nonsense.
1672 {"Empty", []byte{}, "text/plain; charset=utf-8"},
1673 {"Binary", []byte{1, 2, 3}, "application/octet-stream"},
1674
1675 {"HTML document #1", []byte(`<HtMl><bOdY>blah blah blah</body></html>`), "text/html; charset=utf-8"},
1676 {"HTML document #2", []byte(`<HTML></HTML>`), "text/html; charset=utf-8"},
1677 {"HTML document #3 (leading whitespace)", []byte(` <!DOCTYPE HTML>...`), "text/html; charset=utf-8"},
1678 {"HTML document #4 (leading CRLF)", []byte("\r\n<html>..."), "text/html; charset=utf-8"},
1679
1680 {"Plain text", []byte(`This is not HTML. It has ☃ though.`), "text/plain; charset=utf-8"},
1681
1682 {"XML", []byte("\n<?xml!"), "text/xml; charset=utf-8"},
1683
1684 // Image types.
1685 {"Windows icon", []byte("\x00\x00\x01\x00"), "image/x-icon"},
1686 {"Windows cursor", []byte("\x00\x00\x02\x00"), "image/x-icon"},
1687 {"BMP image", []byte("BM..."), "image/bmp"},
1688 {"GIF 87a", []byte(`GIF87a`), "image/gif"},
1689 {"GIF 89a", []byte(`GIF89a...`), "image/gif"},
1690 {"WEBP image", []byte("RIFF\x00\x00\x00\x00WEBPVP"), "image/webp"},
1691 {"PNG image", []byte("\x89PNG\x0D\x0A\x1A\x0A"), "image/png"},
1692 {"JPEG image", []byte("\xFF\xD8\xFF"), "image/jpeg"},
1693
1694 // Audio types.
1695 {"MIDI audio", []byte("MThd\x00\x00\x00\x06\x00\x01"), "audio/midi"},
1696 {"MP3 audio/MPEG audio", []byte("ID3\x03\x00\x00\x00\x00\x0f"), "audio/mpeg"},
1697 {"WAV audio #1", []byte("RIFFb\xb8\x00\x00WAVEfmt \x12\x00\x00\x00\x06"), "audio/wave"},
1698 {"WAV audio #2", []byte("RIFF,\x00\x00\x00WAVEfmt \x12\x00\x00\x00\x06"), "audio/wave"},
1699 {"AIFF audio #1", []byte("FORM\x00\x00\x00\x00AIFFCOMM\x00\x00\x00\x12\x00\x01\x00\x00\x57\x55\x00\x10\x40\x0d\xf3\x34"), "audio/aiff"},
1700
1701 {"OGG audio", []byte("OggS\x00\x02\x00\x00\x00\x00\x00\x00\x00\x00\x7e\x46\x00\x00\x00\x00\x00\x00\x1f\xf6\xb4\xfc\x01\x1e\x01\x76\x6f\x72"), "application/ogg"},
1702 {"Must not match OGG", []byte("owow\x00"), "application/octet-stream"},
1703 {"Must not match OGG", []byte("oooS\x00"), "application/octet-stream"},
1704 {"Must not match OGG", []byte("oggS\x00"), "application/octet-stream"},
1705
1706 // Video types.
1707 {"MP4 video", []byte("\x00\x00\x00\x18ftypmp42\x00\x00\x00\x00mp42isom<\x06t\xbfmdat"), "video/mp4"},
1708 {"AVI video #1", []byte("RIFF,O\n\x00AVI LISTÀ"), "video/avi"},
1709 {"AVI video #2", []byte("RIFF,\n\x00\x00AVI LISTÀ"), "video/avi"},
1710
1711 // Font types.
1712 // {"MS.FontObject", []byte("\x00\x00")},
1713 {"TTF sample I", []byte("\x00\x01\x00\x00\x00\x17\x01\x00\x00\x04\x01\x60\x4f"), "font/ttf"},
1714 {"TTF sample II", []byte("\x00\x01\x00\x00\x00\x0e\x00\x80\x00\x03\x00\x60\x46"), "font/ttf"},
1715
1716 {"OTTO sample I", []byte("\x4f\x54\x54\x4f\x00\x0e\x00\x80\x00\x03\x00\x60\x42\x41\x53\x45"), "font/otf"},
1717
1718 {"woff sample I", []byte("\x77\x4f\x46\x46\x00\x01\x00\x00\x00\x00\x30\x54\x00\x0d\x00\x00"), "font/woff"},
1719 {"woff2 sample", []byte("\x77\x4f\x46\x32\x00\x01\x00\x00\x00"), "font/woff2"},
1720 {"wasm sample", []byte("\x00\x61\x73\x6d\x01\x00"), "application/wasm"},
1721
1722 // Archive types
1723 {"RAR v1.5-v4.0", []byte("Rar!\x1A\x07\x00"), "application/x-rar-compressed"},
1724 {"RAR v5+", []byte("Rar!\x1A\x07\x01\x00"), "application/x-rar-compressed"},
1725 {"Incorrect RAR v1.5-v4.0", []byte("Rar \x1A\x07\x00"), "application/octet-stream"},
1726 {"Incorrect RAR v5+", []byte("Rar \x1A\x07\x01\x00"), "application/octet-stream"},
1727 }
1728
1729 func TestNoContentTypeWhenNoContent(t *testing.T) {
1730 handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
1731 w.WriteHeader(http.StatusNoContent)
1732 })
1733
1734 wrapper, err := NewWrapper()
1735 assertNil(t, err)
1736
1737 req, _ := http.NewRequest("GET", "/", nil)
1738 req.Header.Set("Accept-Encoding", "gzip")
1739 resp := httptest.NewRecorder()
1740 wrapper(handler).ServeHTTP(resp, req)
1741 res := resp.Result()
1742
1743 assertEqual(t, http.StatusNoContent, res.StatusCode)
1744 assertEqual(t, "", res.Header.Get("Content-Type"))
1745
1746 }
1747
1748 func TestNoContentTypeWhenNoBody(t *testing.T) {
1749 handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
1750 w.WriteHeader(http.StatusOK)
1751 })
1752
1753 wrapper, err := NewWrapper()
1754 assertNil(t, err)
1755
1756 req, _ := http.NewRequest("GET", "/", nil)
1757 req.Header.Set("Accept-Encoding", "gzip")
1758 resp := httptest.NewRecorder()
1759 wrapper(handler).ServeHTTP(resp, req)
1760 res := resp.Result()
1761
1762 assertEqual(t, http.StatusOK, res.StatusCode)
1763 assertEqual(t, "", res.Header.Get("Content-Type"))
1764
1765 }
1766
1767 func TestContentTypeDetect(t *testing.T) {
1768 for _, tt := range sniffTests {
1769 t.Run(tt.desc, func(t *testing.T) {
1770 handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
1771 w.WriteHeader(http.StatusOK)
1772 for i := range tt.data {
1773 // Do one byte writes...
1774 w.Write([]byte{tt.data[i]})
1775 }
1776 w.Write(testBody)
1777 })
1778
1779 wrapper, err := NewWrapper()
1780 assertNil(t, err)
1781
1782 req, _ := http.NewRequest("GET", "/whatever", nil)
1783 req.Header.Set("Accept-Encoding", "gzip")
1784 resp := httptest.NewRecorder()
1785 wrapper(handler).ServeHTTP(resp, req)
1786 res := resp.Result()
1787
1788 assertEqual(t, 200, res.StatusCode)
1789 assertEqual(t, tt.contentType, res.Header.Get("Content-Type"))
1790 shouldGZ := DefaultContentTypeFilter(tt.contentType)
1791 if shouldGZ {
1792 assertEqual(t, "gzip", res.Header.Get("Content-Encoding"))
1793 } else {
1794 assertNotEqual(t, "gzip", res.Header.Get("Content-Encoding"))
1795 }
1796 })
1797 t.Run(tt.desc+"empty", func(t *testing.T) {
1798 handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
1799 w.Header().Set("Content-Type", "")
1800 w.WriteHeader(http.StatusOK)
1801 for i := range tt.data {
1802 // Do one byte writes...
1803 w.Write([]byte{tt.data[i]})
1804 }
1805 w.Write(testBody)
1806 })
1807
1808 wrapper, err := NewWrapper()
1809 assertNil(t, err)
1810
1811 req, _ := http.NewRequest("GET", "/whatever", nil)
1812 req.Header.Set("Accept-Encoding", "gzip")
1813 resp := httptest.NewRecorder()
1814 wrapper(handler).ServeHTTP(resp, req)
1815 res := resp.Result()
1816
1817 assertEqual(t, 200, res.StatusCode)
1818 // Is Content-Type still empty?
1819 assertEqual(t, "", res.Header.Get("Content-Type"))
1820 shouldGZ := DefaultContentTypeFilter(tt.contentType)
1821 if shouldGZ {
1822 assertEqual(t, "gzip", res.Header.Get("Content-Encoding"))
1823 } else {
1824 assertNotEqual(t, "gzip", res.Header.Get("Content-Encoding"))
1825 }
1826 })
1827 t.Run(tt.desc+"flush", func(t *testing.T) {
1828 handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
1829 w.Header().Set("Content-Type", "")
1830 w.WriteHeader(http.StatusOK)
1831 for i := range tt.data {
1832 // Do one byte writes...
1833 w.Write([]byte{tt.data[i]})
1834 }
1835 w.(http.Flusher).Flush()
1836 w.Write(testBody)
1837 })
1838
1839 wrapper, err := NewWrapper()
1840 assertNil(t, err)
1841
1842 req, _ := http.NewRequest("GET", "/whatever", nil)
1843 req.Header.Set("Accept-Encoding", "gzip")
1844 resp := httptest.NewRecorder()
1845 wrapper(handler).ServeHTTP(resp, req)
1846 res := resp.Result()
1847
1848 assertEqual(t, 200, res.StatusCode)
1849 // Is Content-Type still empty?
1850 assertEqual(t, "", res.Header.Get("Content-Type"))
1851 shouldGZ := DefaultContentTypeFilter(tt.contentType)
1852 if shouldGZ {
1853 assertEqual(t, "gzip", res.Header.Get("Content-Encoding"))
1854 } else {
1855 assertNotEqual(t, "gzip", res.Header.Get("Content-Encoding"))
1856 }
1857 })
1858 }
1859 }
1860
1861 // --------------------------------------------------------------------
1862
1863 func BenchmarkGzipHandler_S2k(b *testing.B) {
1864 benchmark(b, false, 2048, CompressionLevel(gzip.DefaultCompression))
1865 }
1866 func BenchmarkGzipHandler_S20k(b *testing.B) {
1867 benchmark(b, false, 20480, CompressionLevel(gzip.DefaultCompression))
1868 }
1869 func BenchmarkGzipHandler_S100k(b *testing.B) {
1870 benchmark(b, false, 102400, CompressionLevel(gzip.DefaultCompression))
1871 }
1872 func BenchmarkGzipHandler_P2k(b *testing.B) {
1873 benchmark(b, true, 2048, CompressionLevel(gzip.DefaultCompression))
1874 }
1875 func BenchmarkGzipHandler_P20k(b *testing.B) {
1876 benchmark(b, true, 20480, CompressionLevel(gzip.DefaultCompression))
1877 }
1878 func BenchmarkGzipHandler_P100k(b *testing.B) {
1879 benchmark(b, true, 102400, CompressionLevel(gzip.DefaultCompression))
1880 }
1881
1882 func BenchmarkGzipBestSpeedHandler_S2k(b *testing.B) {
1883 benchmark(b, false, 2048, CompressionLevel(gzip.BestSpeed))
1884 }
1885 func BenchmarkGzipBestSpeedHandler_S20k(b *testing.B) {
1886 benchmark(b, false, 20480, CompressionLevel(gzip.BestSpeed))
1887 }
1888 func BenchmarkGzipBestSpeedHandler_S100k(b *testing.B) {
1889 benchmark(b, false, 102400, CompressionLevel(gzip.BestSpeed))
1890 }
1891 func BenchmarkGzipBestSpeedHandler_P2k(b *testing.B) {
1892 benchmark(b, true, 2048, CompressionLevel(gzip.BestSpeed))
1893 }
1894 func BenchmarkGzipBestSpeedHandler_P20k(b *testing.B) {
1895 benchmark(b, true, 20480, CompressionLevel(gzip.BestSpeed))
1896 }
1897 func BenchmarkGzipBestSpeedHandler_P100k(b *testing.B) {
1898 benchmark(b, true, 102400, CompressionLevel(gzip.BestSpeed))
1899 }
1900
1901 func Benchmark2kJitter(b *testing.B) {
1902 benchmark(b, false, 2048, CompressionLevel(gzip.BestSpeed), RandomJitter(32, 0, false))
1903 }
1904
1905 func Benchmark2kJitterParanoid(b *testing.B) {
1906 benchmark(b, false, 2048, CompressionLevel(gzip.BestSpeed), RandomJitter(32, 0, true))
1907 }
1908
1909 func Benchmark2kJitterRNG(b *testing.B) {
1910 benchmark(b, false, 2048, CompressionLevel(gzip.BestSpeed), RandomJitter(32, -1, false))
1911 }
1912
1913 func Benchmark2kZstd(b *testing.B) {
1914 benchmarkZstd(b, false, 2048, EnableGzip(false))
1915 }
1916
1917 func Benchmark2kZstdJitter(b *testing.B) {
1918 benchmarkZstd(b, false, 2048, EnableGzip(false), RandomJitter(32, 0, false))
1919 }
1920
1921 func Benchmark2kZstdJitterParanoid(b *testing.B) {
1922 benchmarkZstd(b, false, 2048, EnableGzip(false), RandomJitter(32, 0, true))
1923 }
1924
1925 func Benchmark2kZstdJitterRNG(b *testing.B) {
1926 benchmarkZstd(b, false, 2048, EnableGzip(false), RandomJitter(32, -1, false))
1927 }
1928
1929 func BenchmarkZstdHandler_S2k(b *testing.B) {
1930 benchmarkZstd(b, false, 2048, EnableGzip(false))
1931 }
1932 func BenchmarkZstdHandler_S20k(b *testing.B) {
1933 benchmarkZstd(b, false, 20480, EnableGzip(false))
1934 }
1935 func BenchmarkZstdHandler_S100k(b *testing.B) {
1936 benchmarkZstd(b, false, 102400, EnableGzip(false))
1937 }
1938 func BenchmarkZstdHandler_P2k(b *testing.B) {
1939 benchmarkZstd(b, true, 2048, EnableGzip(false))
1940 }
1941 func BenchmarkZstdHandler_P20k(b *testing.B) {
1942 benchmarkZstd(b, true, 20480, EnableGzip(false))
1943 }
1944 func BenchmarkZstdHandler_P100k(b *testing.B) {
1945 benchmarkZstd(b, true, 102400, EnableGzip(false))
1946 }
1947
1948 // --------------------------------------------------------------------
1949
1950 func gzipStrLevel(s []byte, lvl int) []byte {
1951 var b bytes.Buffer
1952 w, _ := gzip.NewWriterLevel(&b, lvl)
1953 w.Write(s)
1954 w.Close()
1955 return b.Bytes()
1956 }
1957
1958 func benchmark(b *testing.B, parallel bool, size int, opts ...option) {
1959 bin, err := os.ReadFile("testdata/benchmark.json")
1960 if err != nil {
1961 b.Fatal(err)
1962 }
1963
1964 req, _ := http.NewRequest("GET", "/whatever", nil)
1965 req.Header.Set("Accept-Encoding", "gzip")
1966 handler := newTestHandlerLevel(bin[:size], opts...)
1967
1968 b.ReportAllocs()
1969 b.SetBytes(int64(size))
1970 if parallel {
1971 b.ResetTimer()
1972 b.RunParallel(func(pb *testing.PB) {
1973 for pb.Next() {
1974 runBenchmark(b, req, handler)
1975 }
1976 })
1977 } else {
1978 b.ResetTimer()
1979 for i := 0; i < b.N; i++ {
1980 runBenchmark(b, req, handler)
1981 }
1982 }
1983 }
1984
1985 func benchmarkZstd(b *testing.B, parallel bool, size int, opts ...option) {
1986 bin, err := os.ReadFile("testdata/benchmark.json")
1987 if err != nil {
1988 b.Fatal(err)
1989 }
1990
1991 req, _ := http.NewRequest("GET", "/whatever", nil)
1992 req.Header.Set("Accept-Encoding", "zstd")
1993 handler := newTestHandlerLevel(bin[:size], opts...)
1994
1995 b.ReportAllocs()
1996 b.SetBytes(int64(size))
1997 if parallel {
1998 b.ResetTimer()
1999 b.RunParallel(func(pb *testing.PB) {
2000 for pb.Next() {
2001 runBenchmark(b, req, handler)
2002 }
2003 })
2004 } else {
2005 b.ResetTimer()
2006 for i := 0; i < b.N; i++ {
2007 runBenchmark(b, req, handler)
2008 }
2009 }
2010 }
2011
2012 func runBenchmark(b *testing.B, req *http.Request, handler http.Handler) {
2013 res := httptest.NewRecorder()
2014 handler.ServeHTTP(res, req)
2015 if code := res.Code; code != 200 {
2016 b.Fatalf("Expected 200 but got %d", code)
2017 } else if blen := res.Body.Len(); blen < 500 {
2018 b.Fatalf("Expected complete response body, but got %d bytes", blen)
2019 }
2020 }
2021
2022 func newTestHandler(body []byte) http.Handler {
2023 var gzBuf bytes.Buffer
2024 var zstdBuf bytes.Buffer
2025 gz := gzip.NewWriter(&gzBuf)
2026 gz.Write(body)
2027 gz.Close()
2028 zs, _ := zstd.NewWriter(&zstdBuf)
2029 zs.Write(body)
2030 zs.Close()
2031 return GzipHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
2032 switch r.URL.Path {
2033 case "/gzipped":
2034 // Add header. Write body as is.
2035 w.Header().Set("Content-Encoding", "gzip")
2036 w.Write(body)
2037 case "/zstd":
2038 // Add header. Write body as is.
2039 w.Header().Set("Content-Encoding", "zstd")
2040 w.Write(body)
2041 case "/gzipped/do":
2042 // Add header. Write gzipped body.
2043 w.Header().Set("Content-Encoding", "gzip")
2044 w.Write(gzBuf.Bytes())
2045 case "/zstd/do":
2046 // Add header. Write zstd body.
2047 w.Header().Set("Content-Encoding", "zstd")
2048 w.Write(zstdBuf.Bytes())
2049 default:
2050 w.Write(body)
2051 }
2052 }))
2053 }
2054
2055 func newTestHandlerLevel(body []byte, opts ...option) http.Handler {
2056 wrapper, err := NewWrapper(opts...)
2057 if err != nil {
2058 panic(err)
2059 }
2060 return wrapper(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
2061 switch r.URL.Path {
2062 case "/gzipped":
2063 w.Header().Set("Content-Encoding", "gzip")
2064 w.Write(body)
2065 default:
2066 w.Write(body)
2067 }
2068 }))
2069 }
2070
2071 func TestGzipHandlerNilContentType(t *testing.T) {
2072 // This just exists to provide something for GzipHandler to wrap.
2073 handler := newTestHandler(testBody)
2074
2075 // content-type header not set when provided nil
2076
2077 req, _ := http.NewRequest("GET", "/whatever", nil)
2078 req.Header.Set("Accept-Encoding", "gzip")
2079 res := httptest.NewRecorder()
2080 res.Header()["Content-Type"] = nil
2081 handler.ServeHTTP(res, req)
2082
2083 assertEqual(t, "", res.Header().Get("Content-Type"))
2084 }
2085
2086 // TestZstdHandler tests basic zstd compression.
2087 func TestZstdHandler(t *testing.T) {
2088 handler := newTestHandler(testBody)
2089
2090 req, _ := http.NewRequest("GET", "/whatever", nil)
2091 req.Header.Set("Accept-Encoding", "zstd")
2092 res := httptest.NewRecorder()
2093 handler.ServeHTTP(res, req)
2094
2095 assertEqual(t, http.StatusOK, res.Code)
2096 assertEqual(t, "zstd", res.Header().Get("Content-Encoding"))
2097
2098 // Decompress and verify
2099 dec, err := zstd.NewReader(res.Body)
2100 if err != nil {
2101 t.Fatal(err)
2102 }
2103 got, err := io.ReadAll(dec)
2104 dec.Close()
2105 if err != nil {
2106 t.Fatal(err)
2107 }
2108 if !bytes.Equal(testBody, got) {
2109 t.Errorf("response body mismatch")
2110 }
2111 }
2112
2113 // TestZstdPreferredOverGzip tests that zstd is preferred when both are accepted with equal qvalues.
2114 func TestZstdPreferredOverGzip(t *testing.T) {
2115 handler := newTestHandler(testBody)
2116
2117 req, _ := http.NewRequest("GET", "/whatever", nil)
2118 req.Header.Set("Accept-Encoding", "gzip, zstd")
2119 res := httptest.NewRecorder()
2120 handler.ServeHTTP(res, req)
2121
2122 assertEqual(t, "zstd", res.Header().Get("Content-Encoding"))
2123 }
2124
2125 // TestGzipPreferredByQValue tests that gzip is used when it has higher qvalue.
2126 func TestGzipPreferredByQValue(t *testing.T) {
2127 handler := newTestHandler(testBody)
2128
2129 req, _ := http.NewRequest("GET", "/whatever", nil)
2130 req.Header.Set("Accept-Encoding", "gzip;q=1.0, zstd;q=0.5")
2131 res := httptest.NewRecorder()
2132 handler.ServeHTTP(res, req)
2133
2134 assertEqual(t, "gzip", res.Header().Get("Content-Encoding"))
2135 }
2136
2137 // TestDisableZstd tests that zstd can be disabled.
2138 func TestDisableZstd(t *testing.T) {
2139 wrapper, err := NewWrapper(EnableZstd(false))
2140 if err != nil {
2141 t.Fatal(err)
2142 }
2143 handler := wrapper(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
2144 w.Write(testBody)
2145 }))
2146
2147 req, _ := http.NewRequest("GET", "/", nil)
2148 req.Header.Set("Accept-Encoding", "gzip, zstd")
2149 res := httptest.NewRecorder()
2150 handler.ServeHTTP(res, req)
2151
2152 assertEqual(t, "gzip", res.Header().Get("Content-Encoding"))
2153 }
2154
2155 // TestDisableGzip tests that gzip can be disabled.
2156 func TestDisableGzip(t *testing.T) {
2157 wrapper, err := NewWrapper(EnableGzip(false))
2158 if err != nil {
2159 t.Fatal(err)
2160 }
2161 handler := wrapper(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
2162 w.Write(testBody)
2163 }))
2164
2165 req, _ := http.NewRequest("GET", "/", nil)
2166 req.Header.Set("Accept-Encoding", "gzip, zstd")
2167 res := httptest.NewRecorder()
2168 handler.ServeHTTP(res, req)
2169
2170 assertEqual(t, "zstd", res.Header().Get("Content-Encoding"))
2171 }
2172
2173 // TestZstdLevels tests zstd compression levels.
2174 func TestZstdLevels(t *testing.T) {
2175 levels := []int{
2176 int(zstd.SpeedFastest),
2177 int(zstd.SpeedDefault),
2178 int(zstd.SpeedBetterCompression),
2179 int(zstd.SpeedBestCompression),
2180 }
2181 for _, level := range levels {
2182 t.Run(fmt.Sprintf("level-%d", level), func(t *testing.T) {
2183 wrapper, err := NewWrapper(EnableGzip(false), ZstdCompressionLevel(level))
2184 if err != nil {
2185 t.Fatal(err)
2186 }
2187 handler := wrapper(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
2188 w.Write(testBody)
2189 }))
2190
2191 req, _ := http.NewRequest("GET", "/", nil)
2192 req.Header.Set("Accept-Encoding", "zstd")
2193 res := httptest.NewRecorder()
2194 handler.ServeHTTP(res, req)
2195
2196 assertEqual(t, "zstd", res.Header().Get("Content-Encoding"))
2197
2198 // Decompress and verify
2199 dec, err := zstd.NewReader(res.Body)
2200 if err != nil {
2201 t.Fatalf("zstd.NewReader failed: %v", err)
2202 }
2203 got, err := io.ReadAll(dec)
2204 dec.Close()
2205 if err != nil {
2206 t.Fatalf("io.ReadAll failed: %v", err)
2207 }
2208 if !bytes.Equal(testBody, got) {
2209 t.Errorf("response body mismatch at level %d", level)
2210 }
2211 })
2212 }
2213 }
2214
2215 // TestPreferGzip tests that gzip is preferred when PreferZstd(false) is set.
2216 func TestPreferGzip(t *testing.T) {
2217 wrapper, err := NewWrapper(PreferZstd(false))
2218 if err != nil {
2219 t.Fatal(err)
2220 }
2221 handler := wrapper(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
2222 w.Write(testBody)
2223 }))
2224
2225 req, _ := http.NewRequest("GET", "/", nil)
2226 req.Header.Set("Accept-Encoding", "gzip, zstd")
2227 res := httptest.NewRecorder()
2228 handler.ServeHTTP(res, req)
2229
2230 // With PreferZstd(false), gzip should be selected when qvalues are equal
2231 assertEqual(t, "gzip", res.Header().Get("Content-Encoding"))
2232 }
2233
2234 // TestZstdOnlyClientGetsZstd tests that a zstd-only client gets zstd.
2235 func TestZstdOnlyClientGetsZstd(t *testing.T) {
2236 handler := newTestHandler(testBody)
2237
2238 req, _ := http.NewRequest("GET", "/whatever", nil)
2239 req.Header.Set("Accept-Encoding", "zstd")
2240 res := httptest.NewRecorder()
2241 handler.ServeHTTP(res, req)
2242
2243 assertEqual(t, "zstd", res.Header().Get("Content-Encoding"))
2244 }
2245
2246 // TestGzipOnlyClientGetsGzip tests that a gzip-only client gets gzip.
2247 func TestGzipOnlyClientGetsGzip(t *testing.T) {
2248 handler := newTestHandler(testBody)
2249
2250 req, _ := http.NewRequest("GET", "/whatever", nil)
2251 req.Header.Set("Accept-Encoding", "gzip")
2252 res := httptest.NewRecorder()
2253 handler.ServeHTTP(res, req)
2254
2255 assertEqual(t, "gzip", res.Header().Get("Content-Encoding"))
2256 }
2257
2258 // TestSelectEncodingFunction tests the selectEncoding function directly.
2259 func TestSelectEncodingFunction(t *testing.T) {
2260 tests := []struct {
2261 name string
2262 acceptEnc string
2263 gzipEnabled bool
2264 zstdEnabled bool
2265 preferZstd bool
2266 want encoding
2267 }{
2268 {"no-accept-encoding", "", true, true, true, encodingNone},
2269 {"gzip-only-accepts-gzip", "gzip", true, true, true, encodingGzip},
2270 {"zstd-only-accepts-zstd", "zstd", true, true, true, encodingZstd},
2271 {"both-prefers-zstd", "gzip, zstd", true, true, true, encodingZstd},
2272 {"both-prefers-gzip", "gzip, zstd", true, true, false, encodingGzip},
2273 {"zstd-higher-qvalue", "gzip;q=0.5, zstd;q=1.0", true, true, false, encodingZstd},
2274 {"gzip-higher-qvalue", "gzip;q=1.0, zstd;q=0.5", true, true, true, encodingGzip},
2275 {"gzip-disabled", "gzip, zstd", false, true, true, encodingZstd},
2276 {"zstd-disabled", "gzip, zstd", true, false, true, encodingGzip},
2277 {"both-disabled", "gzip, zstd", false, false, true, encodingNone},
2278 {"accepts-neither", "br", true, true, true, encodingNone},
2279 }
2280
2281 for _, tt := range tests {
2282 t.Run(tt.name, func(t *testing.T) {
2283 req, _ := http.NewRequest("GET", "/", nil)
2284 if tt.acceptEnc != "" {
2285 req.Header.Set("Accept-Encoding", tt.acceptEnc)
2286 }
2287 got := selectEncoding(req, tt.gzipEnabled, tt.zstdEnabled, tt.preferZstd)
2288 if got != tt.want {
2289 t.Errorf("selectEncoding() = %v, want %v", got, tt.want)
2290 }
2291 })
2292 }
2293 }
2294
2295 // TestZstdRandomJitter tests that RandomJitter works with zstd using skippable frames.
2296 func TestZstdRandomJitter(t *testing.T) {
2297 r := httptest.NewRequest("GET", "/", nil)
2298 r.Header.Set("Accept-Encoding", "zstd")
2299
2300 // 4KB input, incompressible to avoid compression variations.
2301 rng := rand.New(rand.NewSource(0))
2302 payload := make([]byte, 4096)
2303 _, err := io.ReadFull(rng, payload)
2304 if err != nil {
2305 t.Fatal(err)
2306 }
2307
2308 // Disable gzip so we're only testing zstd
2309 wrapper, err := NewWrapper(RandomJitter(256, 1024, false), MinSize(10), EnableGzip(false))
2310 if err != nil {
2311 t.Fatal(err)
2312 }
2313 writePayload := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
2314 w.Write(payload)
2315 })
2316
2317 // Get reference without jitter
2318 refWrapper, _ := NewWrapper(MinSize(10), EnableGzip(false))
2319 refHandler := refWrapper(writePayload)
2320 w := httptest.NewRecorder()
2321 refHandler.ServeHTTP(w, r)
2322 result := w.Result()
2323 refBody, err := io.ReadAll(result.Body)
2324 if err != nil {
2325 t.Fatal(err)
2326 }
2327 t.Logf("Reference length: %d", len(refBody))
2328
2329 // Get output with jitter
2330 handler := wrapper(writePayload)
2331 w = httptest.NewRecorder()
2332 handler.ServeHTTP(w, r)
2333
2334 result = w.Result()
2335 b, err := io.ReadAll(result.Body)
2336 if err != nil {
2337 t.Fatal(err)
2338 }
2339
2340 if len(refBody) >= len(b) {
2341 t.Fatal("padding was not applied")
2342 }
2343 t.Logf("With jitter length: %d (padding: %d)", len(b), len(b)-len(refBody))
2344
2345 // Verify the output can still be decompressed
2346 dec, err := zstd.NewReader(bytes.NewReader(b))
2347 if err != nil {
2348 t.Fatal(err)
2349 }
2350 decoded, err := io.ReadAll(dec)
2351 dec.Close()
2352 if err != nil {
2353 t.Fatal(err)
2354 }
2355 if !bytes.Equal(decoded, payload) {
2356 t.Error("decompressed data doesn't match original")
2357 }
2358
2359 // Verify same input produces same jitter (content-aware)
2360 w = httptest.NewRecorder()
2361 handler.ServeHTTP(w, r)
2362 result = w.Result()
2363 b2, err := io.ReadAll(result.Body)
2364 if err != nil {
2365 t.Fatal(err)
2366 }
2367 if len(b2) != len(b) {
2368 t.Errorf("jitter should be deterministic for same input: got %d, want %d", len(b2), len(b))
2369 }
2370
2371 // Verify changing content changes jitter
2372 payload[0]++
2373 w = httptest.NewRecorder()
2374 handler.ServeHTTP(w, r)
2375 result = w.Result()
2376 b3, err := io.ReadAll(result.Body)
2377 if err != nil {
2378 t.Fatal(err)
2379 }
2380 // Note: different content may still produce same jitter by chance,
2381 // but over multiple changes it should differ at least once.
2382 changed := len(b3) != len(b)
2383 for i := 0; i < 10 && !changed; i++ {
2384 payload[0]++
2385 w = httptest.NewRecorder()
2386 handler.ServeHTTP(w, r)
2387 result = w.Result()
2388 bx, err := io.ReadAll(result.Body)
2389 if err != nil {
2390 t.Fatal(err)
2391 }
2392 changed = len(bx) != len(b)
2393 }
2394 if !changed {
2395 t.Error("jitter didn't change after 10 content changes")
2396 }
2397 }
2398
2399 // This test is an adapted version of net/http/httputil.Test1xxResponses test.
2400 func Test1xxResponses(t *testing.T) {
2401 wrapper, _ := NewWrapper()
2402 handler := wrapper(http.HandlerFunc(
2403 func(w http.ResponseWriter, r *http.Request) {
2404 h := w.Header()
2405 h.Add("Link", "</style.css>; rel=preload; as=style")
2406 h.Add("Link", "</script.js>; rel=preload; as=script")
2407 w.WriteHeader(http.StatusEarlyHints)
2408
2409 h.Add("Link", "</foo.js>; rel=preload; as=script")
2410 w.WriteHeader(http.StatusProcessing)
2411
2412 w.Write(testBody)
2413 },
2414 ))
2415
2416 frontend := httptest.NewServer(handler)
2417 defer frontend.Close()
2418 frontendClient := frontend.Client()
2419
2420 checkLinkHeaders := func(t *testing.T, expected, got []string) {
2421 t.Helper()
2422
2423 if len(expected) != len(got) {
2424 t.Errorf("Expected %d link headers; got %d", len(expected), len(got))
2425 }
2426
2427 for i := range expected {
2428 if i >= len(got) {
2429 t.Errorf("Expected %q link header; got nothing", expected[i])
2430
2431 continue
2432 }
2433
2434 if expected[i] != got[i] {
2435 t.Errorf("Expected %q link header; got %q", expected[i], got[i])
2436 }
2437 }
2438 }
2439
2440 var respCounter uint8
2441 trace := &httptrace.ClientTrace{
2442 Got1xxResponse: func(code int, header textproto.MIMEHeader) error {
2443 switch code {
2444 case http.StatusEarlyHints:
2445 checkLinkHeaders(t, []string{"</style.css>; rel=preload; as=style", "</script.js>; rel=preload; as=script"}, header["Link"])
2446 case http.StatusProcessing:
2447 checkLinkHeaders(t, []string{"</style.css>; rel=preload; as=style", "</script.js>; rel=preload; as=script", "</foo.js>; rel=preload; as=script"}, header["Link"])
2448 default:
2449 t.Error("Unexpected 1xx response")
2450 }
2451
2452 respCounter++
2453
2454 return nil
2455 },
2456 }
2457 req, _ := http.NewRequestWithContext(httptrace.WithClientTrace(context.Background(), trace), "GET", frontend.URL, nil)
2458 req.Header.Set("Accept-Encoding", "gzip")
2459
2460 res, err := frontendClient.Do(req)
2461 if err != nil {
2462 t.Fatalf("Get: %v", err)
2463 }
2464
2465 defer res.Body.Close()
2466
2467 if respCounter != 2 {
2468 t.Errorf("Expected 2 1xx responses; got %d", respCounter)
2469 }
2470 checkLinkHeaders(t, []string{"</style.css>; rel=preload; as=style", "</script.js>; rel=preload; as=script", "</foo.js>; rel=preload; as=script"}, res.Header["Link"])
2471
2472 assertEqual(t, "gzip", res.Header.Get("Content-Encoding"))
2473
2474 body, _ := io.ReadAll(res.Body)
2475 assertEqual(t, gzipStrLevel(testBody, gzip.DefaultCompression), body)
2476 }
2477
2478 func TestContentTypeDetectWithJitter(t *testing.T) {
2479 t.Parallel()
2480 handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
2481 content := `<!DOCTYPE html>` + strings.Repeat("foo", 400)
2482 w.Write([]byte(content))
2483 })
2484
2485 for _, tc := range []struct {
2486 name string
2487 wrapper func(http.Handler) (http.Handler, error)
2488 }{
2489 {
2490 name: "no wrapping",
2491 wrapper: func(h http.Handler) (http.Handler, error) {
2492 return h, nil
2493 },
2494 },
2495 {
2496 name: "default",
2497 wrapper: func(h http.Handler) (http.Handler, error) {
2498 wrapper, err := NewWrapper()
2499 if err != nil {
2500 return nil, err
2501 }
2502 return wrapper(h), nil
2503 },
2504 },
2505 {
2506 name: "jitter, default buffer",
2507 wrapper: func(h http.Handler) (http.Handler, error) {
2508 wrapper, err := NewWrapper(RandomJitter(32, 0, false))
2509 if err != nil {
2510 return nil, err
2511 }
2512 return wrapper(h), nil
2513 },
2514 },
2515 {
2516 name: "jitter, small buffer",
2517 wrapper: func(h http.Handler) (http.Handler, error) {
2518 wrapper, err := NewWrapper(RandomJitter(32, DefaultMinSize, false))
2519 if err != nil {
2520 return nil, err
2521 }
2522 return wrapper(h), nil
2523 },
2524 },
2525 } {
2526 t.Run(tc.name, func(t *testing.T) {
2527 t.Parallel()
2528
2529 handler, err := tc.wrapper(handler)
2530 assertNil(t, err)
2531
2532 req, resp := httptest.NewRequest(http.MethodGet, "/", nil), httptest.NewRecorder()
2533 req.Header.Add("Accept-Encoding", "gzip")
2534
2535 handler.ServeHTTP(resp, req)
2536
2537 assertEqual(t, "text/html; charset=utf-8", resp.Header().Get("Content-Type"))
2538 })
2539 }
2540 }