-
Notifications
You must be signed in to change notification settings - Fork 50
/
compression_io.go
96 lines (73 loc) · 1.88 KB
/
compression_io.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 httpserver
import (
"compress/gzip"
"io"
"github.com/gin-gonic/gin"
"github.com/hashicorp/go-multierror"
)
type countingBodyWriter struct {
gin.ResponseWriter
writtenBytes int
}
func NewCountingBodyWriter(writer gin.ResponseWriter) (gin.ResponseWriter, *int) {
result := &countingBodyWriter{
ResponseWriter: writer,
writtenBytes: 0,
}
return result, &result.writtenBytes
}
func (r *countingBodyWriter) WriteString(s string) (n int, err error) {
writtenBytes, err := r.ResponseWriter.WriteString(s)
r.writtenBytes += writtenBytes
return writtenBytes, err
}
func (r *countingBodyWriter) Write(p []byte) (n int, err error) {
writtenBytes, err := r.ResponseWriter.Write(p)
r.writtenBytes += writtenBytes
return writtenBytes, err
}
type countingBodyReader struct {
io.ReadCloser
readBytes int
}
func NewCountingBodyReader(reader io.ReadCloser) (io.ReadCloser, *int) {
result := &countingBodyReader{
ReadCloser: reader,
readBytes: 0,
}
return result, &result.readBytes
}
func (r *countingBodyReader) Read(p []byte) (int, error) {
readBytes, err := r.ReadCloser.Read(p)
r.readBytes += readBytes
return readBytes, err
}
type gzipBodyReader struct {
body io.Closer
reader *gzip.Reader
readBytes int
}
func NewGZipBodyReader(body io.ReadCloser) (io.ReadCloser, *int, error) {
reader, err := gzip.NewReader(body)
result := &gzipBodyReader{
body: body,
reader: reader,
readBytes: 0,
}
return result, &result.readBytes, err
}
func (r *gzipBodyReader) Read(p []byte) (int, error) {
readBytes, err := r.reader.Read(p)
r.readBytes += readBytes
return readBytes, err
}
func (r *gzipBodyReader) Close() error {
var result *multierror.Error
if err := r.reader.Close(); err != nil {
result = multierror.Append(result, err)
}
if err := r.body.Close(); err != nil {
result = multierror.Append(result, err)
}
return result.ErrorOrNil()
}