-
Notifications
You must be signed in to change notification settings - Fork 0
/
response.go
114 lines (92 loc) · 2.26 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
package kid
import (
"bufio"
"net"
"net/http"
)
type (
// ResponseWriter is a wrapper for http.ResponseWriter
// to make using http.ResponseWriter's methods easier.
ResponseWriter interface {
http.ResponseWriter
http.Hijacker
http.Flusher
// WriteHeaderNow writes status code.
WriteHeaderNow()
// Size returns number of bytes written to response.
Size() int
// Written returns true if response has already been written otherwise returns false.
Written() bool
// Status returns the status code.
Status() int
}
// response implements ResponseWriter.
response struct {
http.ResponseWriter
written bool
status int
size int
}
)
// Verifying interface compliance.
var _ ResponseWriter = (*response)(nil)
// newResponse returns a new response writer.
func newResponse(w http.ResponseWriter) ResponseWriter {
response := response{
ResponseWriter: w,
status: http.StatusOK,
}
return &response
}
// WriteHeader sets status code.
func (r *response) WriteHeader(code int) {
if r.Written() {
return
}
r.status = code
}
// WriteHeaderNow writes status code.
// Status code should already be specified using response.WriteHeader method.
func (r *response) WriteHeaderNow() {
if r.Written() {
return
}
r.written = true
r.ResponseWriter.WriteHeader(r.status)
}
// Write writes byte data to response.
func (r *response) Write(b []byte) (int, error) {
r.WriteHeaderNow()
n, err := r.ResponseWriter.Write(b)
r.size += n
return n, err
}
// Size returns number of bytes written.
func (r *response) Size() int {
return r.size
}
// Written returns true if response has already been written otherwise returns false.
func (r *response) Written() bool {
return r.written
}
// Status returns the status code.
func (r *response) Status() int {
return r.status
}
// Flush implements the http.Flusher interface.
func (r *response) Flush() {
r.WriteHeaderNow()
r.ResponseWriter.(http.Flusher).Flush()
}
// Hijack implements the http.Hijacker interface.
func (r *response) Hijack() (net.Conn, *bufio.ReadWriter, error) {
r.written = true
return r.ResponseWriter.(http.Hijacker).Hijack()
}
// clone clones the current response instance.
//
// No writes are permitted.
func (r response) clone() *response {
r.ResponseWriter = nil
return &r
}