forked from labstack/echo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
compress.go
74 lines (64 loc) · 1.55 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package middleware
import (
"bufio"
"compress/gzip"
"io"
"io/ioutil"
"net"
"net/http"
"strings"
"sync"
"github.com/labstack/echo"
"github.com/labstack/echo/engine"
)
type (
gzipWriter struct {
io.Writer
engine.Response
}
)
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)
}
func (w gzipWriter) Flush() error {
return w.Writer.(*gzip.Writer).Flush()
}
func (w gzipWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
return w.Response.(http.Hijacker).Hijack()
}
func (w *gzipWriter) CloseNotify() <-chan bool {
return w.Response.(http.CloseNotifier).CloseNotify()
}
var writerPool = sync.Pool{
New: func() interface{} {
return gzip.NewWriter(ioutil.Discard)
},
}
// Gzip returns a middleware which compresses HTTP response using gzip compression
// scheme.
func Gzip() echo.MiddlewareFunc {
return func(h echo.HandlerFunc) echo.HandlerFunc {
scheme := "gzip"
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 := writerPool.Get().(*gzip.Writer)
w.Reset(c.Response().Writer())
defer func() {
w.Close()
writerPool.Put(w)
}()
gw := gzipWriter{Writer: w, Response: c.Response()}
c.Response().Header().Set(echo.ContentEncoding, scheme)
c.Response().SetWriter(gw)
}
if err := h.Handle(c); err != nil {
c.Error(err)
}
return nil
}
}
}