1
0
mirror of https://github.com/labstack/echo.git synced 2024-11-28 08:38:39 +02:00

Content type sniffing for compress middleware

Signed-off-by: Vishal Rana <vr@labstack.com>
This commit is contained in:
Chase Hutchins 2015-06-24 13:36:47 -07:00 committed by Vishal Rana
parent d945de6580
commit 356909c49e
4 changed files with 14 additions and 9 deletions

View File

@ -110,6 +110,7 @@ const (
ContentType = "Content-Type"
Authorization = "Authorization"
Upgrade = "Upgrade"
Vary = "Vary"
//-----------
// Protocols

View File

@ -32,7 +32,6 @@ func BasicAuth(fn BasicValidateFunc) echo.HandlerFunc {
auth := c.Request().Header.Get(echo.Authorization)
l := len(Basic)
he := echo.NewHTTPError(http.StatusBadRequest)
println(auth)
if len(auth) > l+1 && auth[:l] == Basic {
b, err := base64.StdEncoding.DecodeString(auth[l+1:])

View File

@ -1,16 +1,14 @@
package middleware
import (
"bufio"
"compress/gzip"
"io"
"net"
"net/http"
"strings"
"net/http"
"bufio"
"net"
"github.com/labstack/echo"
"io"
)
type (
@ -21,6 +19,9 @@ type (
)
func (w gzipWriter) Write(b []byte) (int, error) {
if w.Header().Get(echo.ContentType) == "" {
w.Header().Set(echo.ContentType, http.DetectContentType(b))
}
return w.Writer.Write(b)
}
@ -43,6 +44,7 @@ func Gzip() echo.MiddlewareFunc {
return func(h echo.HandlerFunc) echo.HandlerFunc {
return func(c *echo.Context) error {
c.Response().Header().Add(echo.Vary, echo.AcceptEncoding)
if strings.Contains(c.Request().Header.Get(echo.AcceptEncoding), scheme) {
w := gzip.NewWriter(c.Response().Writer())
defer w.Close()

View File

@ -16,7 +16,8 @@ func TestGzip(t *testing.T) {
rec := httptest.NewRecorder()
c := echo.NewContext(req, echo.NewResponse(rec), echo.New())
h := func(c *echo.Context) error {
return c.String(http.StatusOK, "test")
c.Response().Write([]byte("test")) // Content-Type sniffing
return nil
}
// Skip if no Accept-Encoding header
@ -24,14 +25,16 @@ func TestGzip(t *testing.T) {
assert.Equal(t, http.StatusOK, rec.Code)
assert.Equal(t, "test", rec.Body.String())
// Gzip
req, _ = http.NewRequest(echo.GET, "/", nil)
req.Header.Set(echo.AcceptEncoding, "gzip")
rec = httptest.NewRecorder()
c = echo.NewContext(req, echo.NewResponse(rec), echo.New())
// Gzip
Gzip()(h)(c)
assert.Equal(t, http.StatusOK, rec.Code)
assert.Equal(t, "gzip", rec.Header().Get(echo.ContentEncoding))
assert.Contains(t, rec.Header().Get(echo.ContentType), echo.TextPlain)
r, err := gzip.NewReader(rec.Body)
defer r.Close()
if assert.NoError(t, err) {