-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
compress.go
80 lines (70 loc) · 1.8 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
package middlewares
import (
"bufio"
"bytes"
"compress/gzip"
"io/ioutil"
"net"
"net/http"
"strings"
"sync"
"github.com/getfider/fider/app/pkg/web"
)
var (
minSize = 1024
)
type gzipResponseWriter struct {
code int
response http.ResponseWriter
writer *gzip.Writer
buffer *bytes.Buffer
}
// Compress returns a middleware which compresses HTTP response using gzip compression
func Compress() web.MiddlewareFunc {
return func(next web.HandlerFunc) web.HandlerFunc {
var pool sync.Pool
pool.New = func() interface{} {
return gzip.NewWriter(ioutil.Discard)
}
return func(c web.Context) error {
res := c.Response
if strings.Contains(c.Request.GetHeader("Accept-Encoding"), "gzip") {
writer := pool.Get().(*gzip.Writer)
defer pool.Put(writer)
gzipResponse := &gzipResponseWriter{response: res, writer: writer, buffer: &bytes.Buffer{}}
c.Response = gzipResponse
defer gzipResponse.Flush()
}
return next(c)
}
}
}
func (w *gzipResponseWriter) Header() http.Header {
return w.response.Header()
}
func (w *gzipResponseWriter) WriteHeader(code int) {
w.code = code
}
func (w *gzipResponseWriter) Write(b []byte) (int, error) {
return w.buffer.Write(b)
}
func (w *gzipResponseWriter) Flush() {
w.Header().Add("Vary", "Accept-Encoding")
if w.buffer.Len() >= minSize {
w.Header().Del("Content-Length")
w.Header().Set("Content-Encoding", "gzip")
w.response.WriteHeader(w.code)
w.writer.Reset(w.response)
w.buffer.WriteTo(w.writer)
w.writer.Close()
} else {
w.response.WriteHeader(w.code)
w.buffer.WriteTo(w.response)
}
}
func (w *gzipResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
return w.response.(http.Hijacker).Hijack()
}
func (w *gzipResponseWriter) CloseNotify() <-chan bool {
return w.response.(http.CloseNotifier).CloseNotify()
}