1
0
mirror of https://github.com/labstack/echo.git synced 2024-12-24 20:14:31 +02:00

Fix flushing in Gzip middleware (#1317)

* Make Gzip response Writer also call Flush of underlying Writer
* Add unit test for chunked responses with Gzip
This commit is contained in:
Hylke Visser 2019-04-16 23:52:06 +03:00 committed by Vishal Rana
parent e3717be4be
commit 69bd47b35f
2 changed files with 47 additions and 0 deletions

View File

@ -111,6 +111,9 @@ func (w *gzipResponseWriter) Write(b []byte) (int, error) {
func (w *gzipResponseWriter) Flush() {
w.Writer.(*gzip.Writer).Flush()
if flusher, ok := w.ResponseWriter.(http.Flusher); ok {
flusher.Flush()
}
}
func (w *gzipResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {

View File

@ -3,6 +3,7 @@ package middleware
import (
"bytes"
"compress/gzip"
"io"
"io/ioutil"
"net/http"
"net/http/httptest"
@ -44,6 +45,49 @@ func TestGzip(t *testing.T) {
buf.ReadFrom(r)
assert.Equal("test", buf.String())
}
chunkBuf := make([]byte, 5)
// Gzip chunked
req = httptest.NewRequest(http.MethodGet, "/", nil)
req.Header.Set(echo.HeaderAcceptEncoding, gzipScheme)
rec = httptest.NewRecorder()
c = e.NewContext(req, rec)
Gzip()(func(c echo.Context) error {
c.Response().Header().Set("Content-Type", "text/event-stream")
c.Response().Header().Set("Transfer-Encoding", "chunked")
// Write and flush the first part of the data
c.Response().Write([]byte("test\n"))
c.Response().Flush()
// Read the first part of the data
assert.True(rec.Flushed)
assert.Equal(gzipScheme, rec.Header().Get(echo.HeaderContentEncoding))
r.Reset(rec.Body)
_, err = io.ReadFull(r, chunkBuf)
assert.NoError(err)
assert.Equal("test\n", string(chunkBuf))
// Write and flush the second part of the data
c.Response().Write([]byte("test\n"))
c.Response().Flush()
_, err = io.ReadFull(r, chunkBuf)
assert.NoError(err)
assert.Equal("test\n", string(chunkBuf))
// Write the final part of the data and return
c.Response().Write([]byte("test"))
return nil
})(c)
buf := new(bytes.Buffer)
defer r.Close()
buf.ReadFrom(r)
assert.Equal("test", buf.String())
}
func TestGzipNoContent(t *testing.T) {