forked from labstack/echo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
compress.go
42 lines (35 loc) · 916 Bytes
/
compress.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package middleware
import (
"compress/gzip"
"io"
"strings"
"net/http"
"github.com/labstack/echo"
)
type (
gzipWriter struct {
io.Writer
http.ResponseWriter
}
)
func (w gzipWriter) Write(b []byte) (int, error) {
return w.Writer.Write(b)
}
// Gzip returns a middleware which compresses HTTP response using gzip compression
// scheme.
func Gzip() echo.MiddlewareFunc {
scheme := "gzip"
return func(h echo.HandlerFunc) echo.HandlerFunc {
return func(c *echo.Context) error {
if (c.Request().Header.Get(echo.Upgrade)) != echo.WebSocket && // Skip for WebSocket
strings.Contains(c.Request().Header.Get(echo.AcceptEncoding), scheme) {
w := gzip.NewWriter(c.Response().Writer())
defer w.Close()
gw := gzipWriter{Writer: w, ResponseWriter: c.Response().Writer()}
c.Response().Header().Set(echo.ContentEncoding, scheme)
c.Response().SetWriter(gw)
}
return h(c)
}
}
}