-
Notifications
You must be signed in to change notification settings - Fork 89
/
compress.go
62 lines (47 loc) · 1.34 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
package http
import (
"bufio"
"bytes"
"compress/gzip"
"io"
)
const (
// CompressorMinimumSize is the required size in bytes that a body exceeds before it is compressed
CompressorMinimumSize = 150
)
type RequestCompressor interface {
Compress(r *Request, body []byte) (io.Reader, error)
}
// NoneCompressor does not compress the request at all.
type NoneCompressor struct{}
// CompressRequest returns a reader for the body to the caller
func (c *NoneCompressor) Compress(r *Request, body []byte) (io.Reader, error) {
buffer := bytes.NewBuffer(body)
r.DelHeader("Content-Encoding")
return buffer, nil
}
// GzipCompressor compresses the body with gzip
type GzipCompressor struct{}
// CompressRequest gzips the body, sets the content encoding header, and returns a reader to the caller
func (c *GzipCompressor) Compress(r *Request, body []byte) (io.Reader, error) {
var err error
// Adaptive compression
if len(body) < CompressorMinimumSize {
buf := bytes.NewBuffer(body)
r.DelHeader("Content-Encoding")
return buf, nil
}
readBuffer := bufio.NewReader(bytes.NewReader(body))
buffer := bytes.NewBuffer([]byte{})
writer := gzip.NewWriter(buffer)
_, err = readBuffer.WriteTo(writer)
if err != nil {
return nil, err
}
err = writer.Close()
if err != nil {
return nil, err
}
r.SetHeader("Content-Encoding", "gzip")
return buffer, nil
}