-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathlimited_reader.go
67 lines (56 loc) · 1.74 KB
/
limited_reader.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
package utility
import (
"io"
"net/http"
"github.com/pkg/errors"
)
const maxRequestSize = 16 * 1024 * 1024 // 16 MB
const maxResponseSize = 16 * 1024 * 1024 // 16 MB
type requestReader struct {
req *http.Request
*io.LimitedReader
}
// NewRequestReader returns an io.ReadCloser closer for the body of an
// *http.Request, using a limited reader internally to avoid unbounded
// reading from the request body. The reader is limited to 16 megabytes.
func NewRequestReader(req *http.Request) io.ReadCloser {
return NewRequestReaderWithSize(req, maxRequestSize)
}
// NewRequestReaderWithSize returns an io.ReadCloser closer for the body of an
// *http.Request with a user-specified size.
func NewRequestReaderWithSize(req *http.Request, size int64) io.ReadCloser {
return &requestReader{
req: req,
LimitedReader: &io.LimitedReader{
R: req.Body,
N: size,
},
}
}
func (r *requestReader) Close() error {
return errors.WithStack(r.req.Body.Close())
}
type responseReader struct {
req *http.Response
*io.LimitedReader
}
// NewResponseReader returns an io.ReadCloser closer for the body of an
// *http.Response, using a limited reader internally to avoid unbounded
// reading from the request body. The reader is limited to 16 megabytes.
func NewResponseReader(req *http.Response) io.ReadCloser {
return NewResponseReaderWithSize(req, maxResponseSize)
}
// NewResponseReaderWithSize returns an io.ReadCloser closer for the body of an
// *http.Response with a user-specified size.
func NewResponseReaderWithSize(req *http.Response, size int64) io.ReadCloser {
return &responseReader{
req: req,
LimitedReader: &io.LimitedReader{
R: req.Body,
N: size,
},
}
}
func (r *responseReader) Close() error {
return errors.WithStack(r.req.Body.Close())
}