forked from labstack/echo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
compress.go
63 lines (56 loc) · 1.32 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
package middleware
import (
"compress/gzip"
"io"
"io/ioutil"
"net/http"
"strings"
"sync"
"github.com/labstack/echo"
"github.com/labstack/echo/engine"
)
type (
GzipOptions struct {
level int
}
gzipResponseWriter struct {
engine.Response
io.Writer
}
)
// Gzip returns a middleware which compresses HTTP response using gzip compression
// scheme.
func Gzip(options ...*GzipOptions) echo.MiddlewareFunc {
return func(next echo.Handler) echo.Handler {
scheme := "gzip"
return echo.HandlerFunc(func(c echo.Context) error {
c.Response().Header().Add(echo.Vary, echo.AcceptEncoding)
if strings.Contains(c.Request().Header().Get(echo.AcceptEncoding), scheme) {
w := pool.Get().(*gzip.Writer)
w.Reset(c.Response().Writer())
defer func() {
w.Close()
pool.Put(w)
}()
g := gzipResponseWriter{Response: c.Response(), Writer: w}
c.Response().Header().Set(echo.ContentEncoding, scheme)
c.Response().SetWriter(g)
}
if err := next.Handle(c); err != nil {
c.Error(err)
}
return nil
})
}
}
func (g gzipResponseWriter) Write(b []byte) (int, error) {
if g.Header().Get(echo.ContentType) == "" {
g.Header().Set(echo.ContentType, http.DetectContentType(b))
}
return g.Writer.Write(b)
}
var pool = sync.Pool{
New: func() interface{} {
return gzip.NewWriter(ioutil.Discard)
},
}