forked from labstack/echo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
compress.go
59 lines (48 loc) · 1.17 KB
/
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package middleware
import (
"compress/gzip"
"strings"
"net/http"
"bufio"
"net"
"github.com/labstack/echo"
"io"
)
type (
gzipWriter struct {
io.Writer
http.ResponseWriter
}
)
func (w gzipWriter) Write(b []byte) (int, error) {
return w.Writer.Write(b)
}
func (w gzipWriter) Flush() {
w.Writer.(*gzip.Writer).Flush()
}
func (w gzipWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
return w.ResponseWriter.(http.Hijacker).Hijack()
}
func (w *gzipWriter) CloseNotify() <-chan bool {
return w.ResponseWriter.(http.CloseNotifier).CloseNotify()
}
// 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 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)
}
if err := h(c); err != nil {
c.Error(err)
}
return nil
}
}
}