2015-05-15 21:29:14 +02:00
|
|
|
package middleware
|
|
|
|
|
|
|
|
import (
|
2015-05-18 07:54:29 +02:00
|
|
|
"compress/gzip"
|
2015-05-15 21:29:14 +02:00
|
|
|
"net/http"
|
|
|
|
"net/http/httptest"
|
|
|
|
"testing"
|
|
|
|
|
2015-05-22 07:48:34 +02:00
|
|
|
"bytes"
|
|
|
|
|
2015-05-15 21:29:14 +02:00
|
|
|
"github.com/labstack/echo"
|
|
|
|
)
|
|
|
|
|
|
|
|
func TestGzip(t *testing.T) {
|
2015-05-18 07:54:29 +02:00
|
|
|
// Empty Accept-Encoding header
|
2015-05-15 21:29:14 +02:00
|
|
|
req, _ := http.NewRequest(echo.GET, "/", nil)
|
|
|
|
w := httptest.NewRecorder()
|
2015-05-20 23:38:51 +02:00
|
|
|
res := echo.NewResponse(w)
|
2015-05-15 21:29:14 +02:00
|
|
|
c := echo.NewContext(req, res, echo.New())
|
2015-05-20 23:38:51 +02:00
|
|
|
h := func(c *echo.Context) error {
|
2015-05-15 21:29:14 +02:00
|
|
|
return c.String(http.StatusOK, "test")
|
2015-05-18 07:54:29 +02:00
|
|
|
}
|
|
|
|
Gzip()(h)(c)
|
|
|
|
s := w.Body.String()
|
|
|
|
if s != "test" {
|
|
|
|
t.Errorf("expected `test`, with empty Accept-Encoding header, got %s.", s)
|
|
|
|
}
|
2015-05-15 21:29:14 +02:00
|
|
|
|
2015-05-18 07:54:29 +02:00
|
|
|
// Content-Encoding header
|
|
|
|
req.Header.Set(echo.AcceptEncoding, "gzip")
|
|
|
|
w = httptest.NewRecorder()
|
2015-05-22 13:40:01 +02:00
|
|
|
c.Response().SetWriter(w)
|
2015-05-18 07:54:29 +02:00
|
|
|
Gzip()(h)(c)
|
|
|
|
ce := w.Header().Get(echo.ContentEncoding)
|
|
|
|
if ce != "gzip" {
|
|
|
|
t.Errorf("expected Content-Encoding header `gzip`, got %d.", ce)
|
2015-05-15 21:29:14 +02:00
|
|
|
}
|
|
|
|
|
2015-05-18 07:54:29 +02:00
|
|
|
// Body
|
2015-05-15 21:29:14 +02:00
|
|
|
r, err := gzip.NewReader(w.Body)
|
|
|
|
defer r.Close()
|
|
|
|
if err != nil {
|
2015-05-22 07:48:34 +02:00
|
|
|
t.Fatal(err)
|
2015-05-15 21:29:14 +02:00
|
|
|
}
|
2015-05-22 07:48:34 +02:00
|
|
|
buf := new(bytes.Buffer)
|
|
|
|
buf.ReadFrom(r)
|
|
|
|
s = buf.String()
|
2015-05-15 21:29:14 +02:00
|
|
|
if s != "test" {
|
2015-05-18 07:54:29 +02:00
|
|
|
t.Errorf("expected body `test`, got %s.", s)
|
2015-05-15 21:29:14 +02:00
|
|
|
}
|
|
|
|
}
|