mirror of
https://github.com/labstack/echo.git
synced 2024-12-24 20:14:31 +02:00
parent
f5f75122ba
commit
562021ed2d
@ -29,6 +29,10 @@ type (
|
||||
}
|
||||
)
|
||||
|
||||
const (
|
||||
gzipScheme = "gzip"
|
||||
)
|
||||
|
||||
var (
|
||||
// DefaultGzipConfig is the default Gzip middleware config.
|
||||
DefaultGzipConfig = GzipConfig{
|
||||
@ -54,8 +58,6 @@ func GzipWithConfig(config GzipConfig) echo.MiddlewareFunc {
|
||||
config.Level = DefaultGzipConfig.Level
|
||||
}
|
||||
|
||||
scheme := "gzip"
|
||||
|
||||
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
||||
return func(c echo.Context) error {
|
||||
if config.Skipper(c) {
|
||||
@ -64,7 +66,7 @@ func GzipWithConfig(config GzipConfig) echo.MiddlewareFunc {
|
||||
|
||||
res := c.Response()
|
||||
res.Header().Add(echo.HeaderVary, echo.HeaderAcceptEncoding)
|
||||
if strings.Contains(c.Request().Header.Get(echo.HeaderAcceptEncoding), scheme) {
|
||||
if strings.Contains(c.Request().Header.Get(echo.HeaderAcceptEncoding), gzipScheme) {
|
||||
rw := res.Writer()
|
||||
w, err := gzip.NewWriterLevel(rw, config.Level)
|
||||
if err != nil {
|
||||
@ -76,13 +78,11 @@ func GzipWithConfig(config GzipConfig) echo.MiddlewareFunc {
|
||||
// nothing is written to body or error is returned.
|
||||
// See issue #424, #407.
|
||||
res.SetWriter(rw)
|
||||
res.Header().Del(echo.HeaderContentEncoding)
|
||||
w.Reset(ioutil.Discard)
|
||||
}
|
||||
w.Close()
|
||||
}()
|
||||
grw := &gzipResponseWriter{Writer: w, ResponseWriter: rw}
|
||||
res.Header().Set(echo.HeaderContentEncoding, scheme)
|
||||
res.SetWriter(grw)
|
||||
}
|
||||
return next(c)
|
||||
@ -94,6 +94,9 @@ func (w *gzipResponseWriter) Write(b []byte) (int, error) {
|
||||
if w.Header().Get(echo.HeaderContentType) == "" {
|
||||
w.Header().Set(echo.HeaderContentType, http.DetectContentType(b))
|
||||
}
|
||||
if w.Header().Get(echo.HeaderContentEncoding) == "" {
|
||||
w.Header().Set(echo.HeaderContentEncoding, gzipScheme)
|
||||
}
|
||||
return w.Writer.Write(b)
|
||||
}
|
||||
|
||||
|
@ -25,12 +25,11 @@ func TestGzip(t *testing.T) {
|
||||
h(c)
|
||||
assert.Equal(t, "test", rec.Body.String())
|
||||
|
||||
// Gzip
|
||||
req, _ = http.NewRequest(echo.GET, "/", nil)
|
||||
req.Header.Set(echo.HeaderAcceptEncoding, "gzip")
|
||||
rec = httptest.NewRecorder()
|
||||
c = e.NewContext(req, rec)
|
||||
|
||||
// Gzip
|
||||
h(c)
|
||||
assert.Equal(t, "gzip", rec.Header().Get(echo.HeaderContentEncoding))
|
||||
assert.Contains(t, rec.Header().Get(echo.HeaderContentType), echo.MIMETextPlain)
|
||||
@ -49,7 +48,7 @@ func TestGzipNoContent(t *testing.T) {
|
||||
rec := httptest.NewRecorder()
|
||||
c := e.NewContext(req, rec)
|
||||
h := Gzip()(func(c echo.Context) error {
|
||||
return c.NoContent(http.StatusOK)
|
||||
return c.NoContent(http.StatusNoContent)
|
||||
})
|
||||
if assert.NoError(t, h(c)) {
|
||||
assert.Empty(t, rec.Header().Get(echo.HeaderContentEncoding))
|
||||
|
Loading…
Reference in New Issue
Block a user