forked from micro-plat/hydra
/
response_writer.go
91 lines (78 loc) · 1.71 KB
/
response_writer.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
package dispatcher
import (
"net/http"
)
const (
noWritten = -1
defaultStatus = 200
)
type ResponseWriter interface {
// Returns the HTTP response status code of the current request.
Status() int
// Returns the number of bytes already written into the response http body.
// See Written()
Size() int
Data() []byte
// Writes the string into the response body.
WriteString(string) (int, error)
WriteHeader(code int)
Write([]byte) (int, error)
// Returns true if the response body was already written.
Written() bool
// Forces to write the http header (status code + headers).
WriteHeaderNow()
Header() http.Header
}
type responseWriter struct {
size int
status int
data []byte
header http.Header
}
func (w *responseWriter) Copy() *responseWriter {
var cp = *w
return &cp
}
func (w *responseWriter) reset() {
w.size = noWritten
w.header = make(map[string][]string)
w.status = defaultStatus
w.data = nil
}
func (w *responseWriter) WriteHeader(code int) {
if code > 0 && w.status != code {
w.status = code
}
}
func (w *responseWriter) WriteHeaderNow() {
if !w.Written() {
w.size = 0
}
}
func (w *responseWriter) Write(data []byte) (n int, err error) {
w.WriteHeaderNow()
w.data = data
w.size += len(data)
return w.size, nil
}
func (w *responseWriter) Header() http.Header {
return w.header
}
func (w *responseWriter) WriteString(s string) (n int, err error) {
w.WriteHeaderNow()
w.data = []byte(s)
w.size += len(w.data)
return w.size, nil
}
func (w *responseWriter) Status() int {
return w.status
}
func (w *responseWriter) Data() []byte {
return w.data
}
func (w *responseWriter) Size() int {
return w.size
}
func (w *responseWriter) Written() bool {
return w.size != noWritten
}