-
-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathrecorder.go
53 lines (45 loc) · 1.11 KB
/
recorder.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
package httpretty
import (
"bytes"
"io"
"net/http"
)
type bodyCloser struct {
r io.Reader
close func() error
}
func (bc *bodyCloser) Read(p []byte) (n int, err error) {
return bc.r.Read(p)
}
func (bc *bodyCloser) Close() error {
return bc.close()
}
func newBodyReaderBuf(buf io.Reader, body io.ReadCloser) *bodyCloser {
return &bodyCloser{
r: io.MultiReader(buf, body),
close: body.Close,
}
}
type responseRecorder struct {
http.ResponseWriter
statusCode int
maxReadableBody int64
size int64
buf *bytes.Buffer
}
// Write the data to the connection as part of an HTTP reply, and records it.
func (rr *responseRecorder) Write(p []byte) (int, error) {
rr.size += int64(len(p))
if rr.maxReadableBody > 0 && rr.size > rr.maxReadableBody {
rr.buf = nil
return rr.ResponseWriter.Write(p)
}
defer rr.buf.Write(p)
return rr.ResponseWriter.Write(p)
}
// WriteHeader sends an HTTP response header with the provided
// status code, and records it.
func (rr *responseRecorder) WriteHeader(statusCode int) {
rr.ResponseWriter.WriteHeader(statusCode)
rr.statusCode = statusCode
}