-
-
Notifications
You must be signed in to change notification settings - Fork 25
/
zstd_test.go
60 lines (46 loc) · 1.44 KB
/
zstd_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package main
import (
"io"
"net/http"
"net/http/httptest"
"testing"
)
// Test handler to wrap in the middleware
func testHandler(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
_, err := w.Write([]byte("Hello, World!"))
if err != nil {
panic(err)
}
}
func TestZstdMiddleware_NoCompression(t *testing.T) {
handler := zstdMiddleware(http.HandlerFunc(testHandler), 3)
req := httptest.NewRequest(http.MethodGet, "/", nil)
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
res := rec.Result()
defer res.Body.Close()
if res.Header.Get("Content-Encoding") != "" {
t.Errorf("expected no Content-Encoding, got %s", res.Header.Get("Content-Encoding"))
}
body, _ := io.ReadAll(res.Body)
if string(body) != "Hello, World!" {
t.Errorf("unexpected body: got %s, want %s", string(body), "Hello, World!")
}
}
func TestZstdMiddleware_WithCompression(t *testing.T) {
handler := zstdMiddleware(http.HandlerFunc(testHandler), 3)
req := httptest.NewRequest(http.MethodGet, "/", nil)
req.Header.Set("Accept-Encoding", "zstd")
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
res := rec.Result()
defer res.Body.Close()
if res.Header.Get("Content-Encoding") != "zstd" {
t.Errorf("expected Content-Encoding to be zstd, got %s", res.Header.Get("Content-Encoding"))
}
body, _ := io.ReadAll(res.Body)
if string(body) == "Hello, World!" {
t.Errorf("response should be compressed, found plaintext in body")
}
}