-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathresponse_writer.go
82 lines (70 loc) · 1.79 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
package napnap
import (
"bufio"
"net"
"net/http"
)
const (
noWritten = -1
defaultStatus = 200
)
// ResponseWriter wraps the original http.ResponseWriter
type ResponseWriter interface {
http.ResponseWriter
ContentLength() int
Status() int
reset(writer http.ResponseWriter) ResponseWriter
}
type responseWriter struct {
http.ResponseWriter
committed bool
status int
contentLength int
}
// NewResponseWriter returns a ResponseWriter which wraps the writer
func NewResponseWriter() ResponseWriter {
return &responseWriter{
status: defaultStatus,
contentLength: noWritten,
}
}
// ContentLength returns size of content length
func (rw *responseWriter) ContentLength() int {
return rw.contentLength
}
// Status returns http status code
func (rw *responseWriter) Status() int {
return rw.status
}
func (rw *responseWriter) Write(b []byte) (int, error) {
if !rw.committed {
// The status will be StatusOK if WriteHeader has not been called yet
rw.WriteHeader(http.StatusOK)
}
n, err := rw.ResponseWriter.Write(b)
rw.contentLength += n
return n, err
}
func (rw *responseWriter) WriteHeader(statusCode int) {
if rw.committed {
_logger.debug("Headers were already written.")
return
}
// Store the status code
rw.status = statusCode
rw.ResponseWriter.WriteHeader(statusCode)
rw.committed = true
}
// Hijack implements the http.Hijacker interface to allow a HTTP handler to
// take over the connection.
// See https://golang.org/pkg/net/http/#Hijacker
func (rw *responseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
return rw.ResponseWriter.(http.Hijacker).Hijack()
}
func (rw *responseWriter) reset(writer http.ResponseWriter) ResponseWriter {
rw.ResponseWriter = writer
rw.contentLength = noWritten
rw.status = defaultStatus
rw.committed = false
return rw
}