github.com/brycereitano/goa@v0.0.0-20170315073847-8ffa6c85e265/middleware/gzip/middleware_test.go (about) 1 package gzip_test 2 3 import ( 4 "bytes" 5 "compress/gzip" 6 "io" 7 "net/http" 8 "strings" 9 10 "golang.org/x/net/context" 11 12 "github.com/goadesign/goa" 13 gzm "github.com/goadesign/goa/middleware/gzip" 14 . "github.com/onsi/ginkgo" 15 . "github.com/onsi/gomega" 16 ) 17 18 type TestResponseWriter struct { 19 ParentHeader http.Header 20 Body []byte 21 Status int 22 } 23 24 func (t *TestResponseWriter) Header() http.Header { 25 return t.ParentHeader 26 } 27 28 func (t *TestResponseWriter) Write(b []byte) (int, error) { 29 t.Body = append(t.Body, b...) 30 return len(b), nil 31 } 32 33 func (t *TestResponseWriter) WriteHeader(s int) { 34 t.Status = s 35 } 36 37 var _ = Describe("Gzip", func() { 38 var ctx context.Context 39 var req *http.Request 40 var rw *TestResponseWriter 41 payload := map[string]interface{}{"payload": 42} 42 43 BeforeEach(func() { 44 var err error 45 req, err = http.NewRequest("POST", "/foo/bar", strings.NewReader(`{"payload":42}`)) 46 req.Header.Set("Accept-Encoding", "gzip") 47 Ω(err).ShouldNot(HaveOccurred()) 48 rw = &TestResponseWriter{ParentHeader: make(http.Header)} 49 50 ctx = goa.NewContext(nil, rw, req, nil) 51 goa.ContextRequest(ctx).Payload = payload 52 }) 53 54 It("encodes response using gzip", func() { 55 h := func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error { 56 resp := goa.ContextResponse(ctx) 57 resp.Write([]byte("gzip me!")) 58 resp.WriteHeader(http.StatusOK) 59 return nil 60 } 61 t := gzm.Middleware(gzip.BestCompression)(h) 62 err := t(ctx, rw, req) 63 Ω(err).ShouldNot(HaveOccurred()) 64 resp := goa.ContextResponse(ctx) 65 Ω(resp.Status).Should(Equal(http.StatusOK)) 66 67 gzr, err := gzip.NewReader(bytes.NewReader(rw.Body)) 68 Ω(err).ShouldNot(HaveOccurred()) 69 buf := bytes.NewBuffer(nil) 70 io.Copy(buf, gzr) 71 Ω(err).ShouldNot(HaveOccurred()) 72 Ω(buf.String()).Should(Equal("gzip me!")) 73 }) 74 75 })