-
Notifications
You must be signed in to change notification settings - Fork 41
/
compression.go
84 lines (72 loc) · 1.71 KB
/
compression.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
package antch
import (
"compress/gzip"
"compress/zlib"
"io"
"net/http"
)
func decompress(name string, rc io.ReadCloser) (io.ReadCloser, bool) {
switch name {
case "gzip":
return &gzipReader{rc: rc}, true
case "deflate":
return &deflateReader{rc: rc}, true
}
return nil, false
}
func compressionHandler(next HttpMessageHandler) HttpMessageHandler {
return HttpMessageHandlerFunc(func(req *http.Request) (*http.Response, error) {
req.Header.Set("Accept-Encoding", "gzip, deflate")
resp, err := next.Send(req)
if err != nil {
return nil, err
}
if rc, ok := decompress(resp.Header.Get("Content-Encoding"), resp.Body); ok {
resp.Header.Del("Content-Encoding")
resp.Header.Del("Content-Length")
resp.Body = rc
resp.ContentLength = -1
resp.Uncompressed = true
}
return resp, err
})
}
// gzipReader is a reader with gzip decompress mode.
type gzipReader struct {
rr io.Reader
rc io.ReadCloser
}
func (z *gzipReader) Read(p []byte) (n int, err error) {
if z.rr == nil {
z.rr, err = gzip.NewReader(z.rc)
if err != nil {
return n, err
}
}
return z.rr.Read(p)
}
func (z *gzipReader) Close() error {
return z.rc.Close()
}
// deflateReader is a reader with deflate decompress mode.
type deflateReader struct {
rr io.Reader
rc io.ReadCloser
}
func (r *deflateReader) Read(p []byte) (n int, err error) {
if r.rr == nil {
r.rr, err = zlib.NewReader(r.rc)
if err != nil {
return n, err
}
}
return r.rr.Read(p)
}
func (r *deflateReader) Close() error {
return r.rc.Close()
}
// CompressionMiddleware is a middleware to allows compressed
// (gzip, deflate) traffic to be sent/received from sites.
func CompressionMiddleware() Middleware {
return Middleware(compressionHandler)
}