1 package httpembed 2 3 import ( 4 "bytes" 5 "compress/gzip" 6 "io" 7 "net/http" 8 "net/http/httptest" 9 "testing" 10 "time" 11 ) 12 13 type compressor struct { 14 buf bytes.Buffer 15 gz gzip.Writer 16 } 17 18 func (c *compressor) Compress(str string) ([]byte, error) { 19 c.buf.Reset() 20 c.gz.Reset(&c.buf) 21 if _, err := io.WriteString(&c.gz, str); err != nil { 22 return nil, err 23 } 24 25 if err := c.gz.Close(); err != nil { 26 return nil, err 27 } 28 29 return c.buf.Bytes(), nil 30 } 31 32 func test(t *testing.T, fn func(test string, buf *bytes.Buffer) http.Handler) { 33 t.Helper() 34 35 c := new(compressor) 36 37 for n, test := range [...]string{ 38 "HELLO", 39 "Hello, World!", 40 "Long! Long! Long! Long! Long! Long! Long! Long! Long! Long! Long! Long! Long! Long! Long! Long! Long! Long! Long! Long! Long! Long! Long! Long! Long! Long! Long! Long! Long! Long! Long! Long! Long! Long! Long! Long! Long! Long! Long! Long! Long! Long! Long! Long! Long! Long! Long! Long! Long! Long! Long! Long! Long! Long! Long! Long! Long! Long! Long! Long! Long! Long! Long! Long! Long! Long! Long! Long! Long! Long! Long! Long! Long! Long! Long! Long! Long! Long! Long! Long! Long! Long! Long! Long!", 41 } { 42 bs, err := c.Compress(test) 43 if err != nil { 44 t.Fatalf("test %d: unexpected error: %s", n+1, err) 45 } 46 h := fn(test, &c.buf) 47 w := httptest.NewRecorder() 48 r := httptest.NewRequest("GET", "/file", nil) 49 h.ServeHTTP(w, r) 50 res := w.Result() 51 b, err := io.ReadAll(res.Body) 52 if err != nil { 53 t.Errorf("test %d.1: unexpected error: %s", n+1, err) 54 continue 55 } else if res.ContentLength != int64(len(test)) { 56 t.Errorf("test %d.1: expecting to read %d bytes, read %d", n+1, len(test), r.ContentLength) 57 continue 58 } else if string(b) != test { 59 t.Errorf("test %d.1: expecting to read %q, got %q", n+1, test, b) 60 continue 61 } 62 r.Header.Set("Accept-Encoding", "gzip") 63 w = httptest.NewRecorder() 64 h.ServeHTTP(w, r) 65 b, err = io.ReadAll(w.Result().Body) 66 if err != nil { 67 t.Errorf("test %d.2: unexpected error: %s", n+1, err) 68 } else if !bytes.Equal(b, bs) { 69 t.Errorf("test %d.2: expecting to read %v, got %v", n+1, bs, b) 70 } 71 } 72 } 73 74 func TestBuffer(t *testing.T) { 75 test(t, func(test string, buf *bytes.Buffer) http.Handler { 76 return HandleBuffer("data.txt", buf.Bytes(), len(test), time.Now()) 77 }) 78 } 79 80 func TestBufferNoSize(t *testing.T) { 81 test(t, func(test string, buf *bytes.Buffer) http.Handler { 82 return HandleBuffer("data.txt", buf.Bytes(), 0, time.Now()) 83 }) 84 } 85 86 func TestReader(t *testing.T) { 87 test(t, func(test string, buf *bytes.Buffer) http.Handler { 88 return HandleReader("data.txt", buf, buf.Len(), len(test), time.Now()) 89 }) 90 } 91 92 func TestReaderNoSize(t *testing.T) { 93 test(t, func(_ string, buf *bytes.Buffer) http.Handler { 94 return HandleReader("data.txt", buf, 0, 0, time.Now()) 95 }) 96 } 97