-
Notifications
You must be signed in to change notification settings - Fork 2
/
response.go
117 lines (100 loc) · 2.47 KB
/
response.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
package tcp
import (
"bytes"
"io"
)
// ResponseWriter interface is used by a TCP handler to write the response.
type ResponseWriter interface {
// Size returns the number of bytes already written into the response body.
// -1: not already written
Size() int
io.WriteCloser
}
func newWriter(wc io.WriteCloser) *responseWriter {
return &responseWriter{
ResponseWriter: wc,
size: noWritten,
}
}
type responseWriter struct {
ResponseWriter io.WriteCloser
size int
}
const noWritten = -1
// Close implements the ResponseWriter interface.
func (r *responseWriter) Close() error {
if r.ResponseWriter == nil {
return nil
}
return r.ResponseWriter.Close()
}
// Size implements the ResponseWriter interface.
func (r *responseWriter) Size() int {
return r.size
}
// Write implements the ResponseWriter interface.
func (r *responseWriter) Write(p []byte) (n int, err error) {
if r.ResponseWriter == nil {
return 0, io.EOF
}
n, err = r.ResponseWriter.Write(p)
r.incr(n)
return
}
// WriteString allows to directly write string.
func (r *responseWriter) WriteString(s string) (n int, err error) {
if r.ResponseWriter == nil {
return 0, io.EOF
}
n, err = io.WriteString(r.ResponseWriter, s)
r.incr(n)
return
}
func (r *responseWriter) incr(n int) {
if r.size == noWritten {
r.size = 0
}
r.size += n
}
func (r *responseWriter) rebase(w io.WriteCloser) {
r.ResponseWriter = w
r.size = noWritten
}
// ResponseRecorder is an implementation of http.ResponseWriter that records its changes.
type ResponseRecorder struct {
// Body is the buffer to which the Handler's Write calls are sent.
Body *bytes.Buffer
}
// NewRecorder returns an initialized writer to record the response.
func NewRecorder() *ResponseRecorder {
return &ResponseRecorder{
Body: new(bytes.Buffer),
}
}
// Close implements the ResponseWriter interface.
func (r *ResponseRecorder) Close() error {
return nil
}
// Size implements the ResponseWriter interface.
func (r *ResponseRecorder) Size() int {
if r == nil || r.Body == nil {
return noWritten
}
return r.Body.Len()
}
// Write implements the ResponseWriter interface.
func (r *ResponseRecorder) Write(p []byte) (n int, err error) {
if r == nil || r.Body == nil {
return 0, io.EOF
}
n, err = r.Body.Write(p)
return
}
// WriteString allows to directly write string.
func (r *ResponseRecorder) WriteString(s string) (n int, err error) {
if r == nil || r.Body == nil {
return 0, io.EOF
}
n, err = r.Body.WriteString(s)
return
}