-
Notifications
You must be signed in to change notification settings - Fork 0
/
gzip_formatter.go
72 lines (63 loc) · 1.56 KB
/
gzip_formatter.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
package shuttle
import (
"compress/gzip"
"io"
"io/ioutil"
"net/http"
"sync"
)
// GzipFormatter is an HTTPFormatter that is built with a
// delegate HTTPFormatter but which compresses the request body
type GzipFormatter struct {
delegate HTTPFormatter
reader *io.PipeReader
writer *io.PipeWriter
once *sync.Once
}
// NewGzipFormatter builds a new GzipFormatter with the supplied delegate
func NewGzipFormatter(delegate HTTPFormatter) *GzipFormatter {
reader, writer := io.Pipe()
f := &GzipFormatter{
delegate: delegate,
reader: reader,
writer: writer,
once: new(sync.Once),
}
return f
}
func (g *GzipFormatter) writeGzip() {
gw := gzip.NewWriter(g.writer)
_, err := io.Copy(gw, g.delegate)
gw.Close()
if err != nil {
g.writer.CloseWithError(err)
} else {
g.writer.Close()
}
}
// MsgCount return the number of messages contained in the formatted batch
func (g *GzipFormatter) MsgCount() int {
return g.delegate.MsgCount()
}
// Request returns a http.Request to be used with a http.Client
// The request has it's body and headers set as necessary
func (g *GzipFormatter) Request() (*http.Request, error) {
request, err := g.delegate.Request()
if err != nil {
return request, err
}
request.Body = ioutil.NopCloser(g)
request.Header.Add("Content-Encoding", "gzip")
return request, nil
}
// Read bytes from the formatter stream
func (g *GzipFormatter) Read(p []byte) (int, error) {
g.once.Do(func() {
go g.writeGzip()
})
return g.reader.Read(p)
}
// Close the stream
func (g *GzipFormatter) Close() error {
return g.reader.Close()
}