-
Notifications
You must be signed in to change notification settings - Fork 0
/
response_writer.go
108 lines (86 loc) · 2.48 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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package accesslog
import (
"bytes"
"net/http"
"time"
)
// ResponseWriter is an interface that extends http.ResponseWriter with
// additional methods that allow you to inspect the response that is being
// written to the client
type ResponseWriter interface {
http.ResponseWriter
// BytesWritten returns the number of bytes written to the client
BytesWritten() int64
// Status returns the HTTP status code that is being written to the client
Status() int
// StartTime returns the time when the downstream handler started processing
StartTime() time.Time
// EndTime returns the time when the downstream handler finished processing
// Calling this method before `End()` returns the zero time
EndTime() time.Time
// End is called when the downsteam handler has finished processing.
End()
}
// ResponseWriterBuilder is an interface that allows you to wrap an existing
// http.ResponseWriter and return a ResponseWriter object
//
// By default `DefaultResponseWriterBuilder` is used.
type ResponseWriterBuilder interface {
Wrap(http.ResponseWriter, *http.Request, bool) ResponseWriter
}
// DefaultResponseWriterBuilder returns the default ResponseWriterBuilder
func DefaultResponseWriterBuilder() ResponseWriterBuilder {
return defaultResponseWriterBuilder{}
}
type defaultResponseWriterBuilder struct{}
func (defaultResponseWriterBuilder) Wrap(w http.ResponseWriter, _ *http.Request, recordResponse bool) ResponseWriter {
rw := &responseWriter{
ResponseWriter: w,
start: time.Now(),
}
if recordResponse {
rw.responseBody = &bytes.Buffer{}
}
return rw
}
type responseWriter struct {
http.ResponseWriter
bytesWritten int64
code int
start time.Time
end time.Time
responseBody *bytes.Buffer
}
func (rw *responseWriter) End() {
rw.end = time.Now()
}
func (rw *responseWriter) WriteHeader(code int) {
rw.code = code
rw.ResponseWriter.WriteHeader(code)
}
func (rw *responseWriter) Write(b []byte) (int, error) {
written, err := rw.ResponseWriter.Write(b)
rw.bytesWritten += int64(written)
if rb := rw.responseBody; rb != nil {
rb.Write(b)
}
return written, err
}
func (rw *responseWriter) BytesWritten() int64 {
return rw.bytesWritten
}
func (rw *responseWriter) Status() int {
return rw.code
}
func (rw *responseWriter) StartTime() time.Time {
return rw.start
}
func (rw *responseWriter) EndTime() time.Time {
return rw.end
}
func (rw *responseWriter) Body() []byte {
if rb := rw.responseBody; rb != nil {
return rb.Bytes()
}
return nil
}