forked from labstack/echo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
compress.go
96 lines (85 loc) · 2.15 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package middleware
import (
"compress/gzip"
"io"
"io/ioutil"
"net/http"
"strings"
"sync"
"github.com/labstack/echo"
"github.com/labstack/echo/engine"
)
type (
// GzipConfig defines the config for gzip middleware.
GzipConfig struct {
// Gzip compression level.
// Optional. Default value -1.
Level int `json:"level"`
}
gzipResponseWriter struct {
engine.Response
io.Writer
}
)
var (
// DefaultGzipConfig is the default gzip middleware config.
DefaultGzipConfig = GzipConfig{
Level: -1,
}
)
// Gzip returns a middleware which compresses HTTP response using gzip compression
// scheme.
func Gzip() echo.MiddlewareFunc {
return GzipWithConfig(DefaultGzipConfig)
}
// GzipWithConfig return gzip middleware from config.
// See: `Gzip()`.
func GzipWithConfig(config GzipConfig) echo.MiddlewareFunc {
// Defaults
if config.Level == 0 {
config.Level = DefaultGzipConfig.Level
}
pool := gzipPool(config)
scheme := "gzip"
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
res := c.Response()
res.Header().Add(echo.HeaderVary, echo.HeaderAcceptEncoding)
if strings.Contains(c.Request().Header().Get(echo.HeaderAcceptEncoding), scheme) {
rw := res.Writer()
gw := pool.Get().(*gzip.Writer)
gw.Reset(rw)
defer func() {
if res.Size() == 0 {
// We have to reset response to it's pristine state when
// nothing is written to body or error is returned.
// See issue #424, #407.
res.SetWriter(rw)
res.Header().Del(echo.HeaderContentEncoding)
gw.Reset(ioutil.Discard)
}
gw.Close()
pool.Put(gw)
}()
g := gzipResponseWriter{Response: res, Writer: gw}
res.Header().Set(echo.HeaderContentEncoding, scheme)
res.SetWriter(g)
}
return next(c)
}
}
}
func (g gzipResponseWriter) Write(b []byte) (int, error) {
if g.Header().Get(echo.HeaderContentType) == "" {
g.Header().Set(echo.HeaderContentType, http.DetectContentType(b))
}
return g.Writer.Write(b)
}
func gzipPool(config GzipConfig) sync.Pool {
return sync.Pool{
New: func() interface{} {
w, _ := gzip.NewWriterLevel(ioutil.Discard, config.Level)
return w
},
}
}