-
Notifications
You must be signed in to change notification settings - Fork 2
/
gzip_test.go
54 lines (47 loc) · 1.31 KB
/
gzip_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package sandwich
import (
"compress/gzip"
"fmt"
"io"
"net/http"
"net/http/httptest"
"testing"
)
func TestGzip(t *testing.T) {
greet := func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hi there!")
}
handler := BuildYourOwn()
handler.Use(Gzip)
handler.Any("/", greet)
resp := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/", nil)
req.Header.Add(headerAcceptEncoding, "gzip")
handler.ServeHTTP(resp, req)
if resp.Header().Get(headerContentEncoding) != "gzip" {
t.Errorf("Not gzip'd? Content-encoding: %q", resp.Header())
}
if resp.Header().Get(headerContentLength) != "" {
t.Errorf("Not supposed to include content-length: %q", resp.Header())
}
r, err := gzip.NewReader(resp.Body)
if err != nil {
t.Fatal(err)
}
defer r.Close()
if body, err := io.ReadAll(r); err != nil {
t.Fatal(err)
} else if string(body) != "Hi there!" {
t.Errorf("Wrong response: %q", string(body))
}
// Also, test without the accept header and make sure it's NOT gzip'd.
resp = httptest.NewRecorder()
req, _ = http.NewRequest("GET", "/", nil)
handler.ServeHTTP(resp, req)
if resp.Header().Get(headerContentEncoding) == "gzip" {
t.Errorf("Unexpectedly gzip'd: Content-encoding: %q", resp.Header())
}
if resp.Body.String() != "Hi there!" {
t.Errorf("Wrong response: %q", resp.Body.String())
}
}