github.com/lingyao2333/mo-zero@v1.4.1/rest/handler/gunziphandler_test.go (about) 1 package handler 2 3 import ( 4 "bytes" 5 "io" 6 "net/http" 7 "net/http/httptest" 8 "strings" 9 "sync" 10 "testing" 11 12 "github.com/lingyao2333/mo-zero/core/codec" 13 "github.com/lingyao2333/mo-zero/rest/httpx" 14 "github.com/stretchr/testify/assert" 15 ) 16 17 func TestGunzipHandler(t *testing.T) { 18 const message = "hello world" 19 var wg sync.WaitGroup 20 wg.Add(1) 21 handler := GunzipHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 22 body, err := io.ReadAll(r.Body) 23 assert.Nil(t, err) 24 assert.Equal(t, string(body), message) 25 wg.Done() 26 })) 27 28 req := httptest.NewRequest(http.MethodPost, "http://localhost", 29 bytes.NewReader(codec.Gzip([]byte(message)))) 30 req.Header.Set(httpx.ContentEncoding, gzipEncoding) 31 resp := httptest.NewRecorder() 32 handler.ServeHTTP(resp, req) 33 assert.Equal(t, http.StatusOK, resp.Code) 34 wg.Wait() 35 } 36 37 func TestGunzipHandler_NoGzip(t *testing.T) { 38 const message = "hello world" 39 var wg sync.WaitGroup 40 wg.Add(1) 41 handler := GunzipHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 42 body, err := io.ReadAll(r.Body) 43 assert.Nil(t, err) 44 assert.Equal(t, string(body), message) 45 wg.Done() 46 })) 47 48 req := httptest.NewRequest(http.MethodPost, "http://localhost", 49 strings.NewReader(message)) 50 resp := httptest.NewRecorder() 51 handler.ServeHTTP(resp, req) 52 assert.Equal(t, http.StatusOK, resp.Code) 53 wg.Wait() 54 } 55 56 func TestGunzipHandler_NoGzipButTelling(t *testing.T) { 57 const message = "hello world" 58 handler := GunzipHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})) 59 req := httptest.NewRequest(http.MethodPost, "http://localhost", 60 strings.NewReader(message)) 61 req.Header.Set(httpx.ContentEncoding, gzipEncoding) 62 resp := httptest.NewRecorder() 63 handler.ServeHTTP(resp, req) 64 assert.Equal(t, http.StatusBadRequest, resp.Code) 65 }