forked from labstack/echo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
compress.go
39 lines (33 loc) · 810 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
package middleware
import (
"compress/gzip"
"io"
"strings"
"github.com/labstack/echo"
)
type (
gzipWriter struct {
io.Writer
*echo.Response
}
)
func (g gzipWriter) Write(b []byte) (int, error) {
return g.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) *echo.HTTPError {
if strings.Contains(c.Request.Header.Get(echo.AcceptEncoding), scheme) {
w := gzip.NewWriter(c.Response.Writer)
defer w.Close()
gw := gzipWriter{Writer: w, Response: c.Response}
c.Response.Header().Set(echo.ContentEncoding, scheme)
c.Response = &echo.Response{Writer: gw}
}
return h(c)
}
}
}