2015-05-15 12:29:14 -07:00
|
|
|
package middleware
|
|
|
|
|
|
|
|
import (
|
2015-05-17 22:54:29 -07:00
|
|
|
"compress/gzip"
|
2015-05-15 12:29:14 -07:00
|
|
|
"net/http"
|
|
|
|
"net/http/httptest"
|
|
|
|
"testing"
|
|
|
|
|
2015-05-21 22:48:34 -07:00
|
|
|
"bytes"
|
|
|
|
|
2015-05-15 12:29:14 -07:00
|
|
|
"github.com/labstack/echo"
|
2015-05-30 10:54:55 -07:00
|
|
|
"github.com/stretchr/testify/assert"
|
2015-05-15 12:29:14 -07:00
|
|
|
)
|
|
|
|
|
|
|
|
func TestGzip(t *testing.T) {
|
2015-05-17 22:54:29 -07:00
|
|
|
// Empty Accept-Encoding header
|
2015-05-15 12:29:14 -07:00
|
|
|
req, _ := http.NewRequest(echo.GET, "/", nil)
|
2015-05-30 10:54:55 -07:00
|
|
|
rec := httptest.NewRecorder()
|
|
|
|
c := echo.NewContext(req, echo.NewResponse(rec), echo.New())
|
2015-05-20 14:38:51 -07:00
|
|
|
h := func(c *echo.Context) error {
|
2015-05-15 12:29:14 -07:00
|
|
|
return c.String(http.StatusOK, "test")
|
2015-05-17 22:54:29 -07:00
|
|
|
}
|
|
|
|
Gzip()(h)(c)
|
2015-05-30 10:54:55 -07:00
|
|
|
assert.Equal(t, http.StatusOK, rec.Code)
|
|
|
|
assert.Equal(t, "test", rec.Body.String())
|
2015-05-15 12:29:14 -07:00
|
|
|
|
2015-05-30 10:54:55 -07:00
|
|
|
// With Accept-Encoding header
|
|
|
|
req, _ = http.NewRequest(echo.GET, "/", nil)
|
2015-05-17 22:54:29 -07:00
|
|
|
req.Header.Set(echo.AcceptEncoding, "gzip")
|
2015-05-30 10:54:55 -07:00
|
|
|
rec = httptest.NewRecorder()
|
|
|
|
c = echo.NewContext(req, echo.NewResponse(rec), echo.New())
|
2015-05-17 22:54:29 -07:00
|
|
|
Gzip()(h)(c)
|
2015-05-30 10:54:55 -07:00
|
|
|
assert.Equal(t, http.StatusOK, rec.Code)
|
|
|
|
assert.Equal(t, "gzip", rec.Header().Get(echo.ContentEncoding))
|
|
|
|
r, err := gzip.NewReader(rec.Body)
|
2015-05-15 12:29:14 -07:00
|
|
|
defer r.Close()
|
2015-05-30 10:54:55 -07:00
|
|
|
if assert.NoError(t, err) {
|
|
|
|
buf := new(bytes.Buffer)
|
|
|
|
buf.ReadFrom(r)
|
|
|
|
assert.Equal(t, "test", buf.String())
|
2015-05-15 12:29:14 -07:00
|
|
|
}
|
|
|
|
}
|