forked from smallstep/certificates
-
Notifications
You must be signed in to change notification settings - Fork 0
/
responselogger.go
113 lines (95 loc) · 2.21 KB
/
responselogger.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
package logging
import (
"bufio"
"net"
"net/http"
)
// ResponseLogger defines an interface that a responseWrite can implement to
// support the capture of the status code, the number of bytes written and
// extra log entry fields.
type ResponseLogger interface {
http.ResponseWriter
Size() int
StatusCode() int
Fields() map[string]interface{}
WithFields(map[string]interface{})
}
// NewResponseLogger wraps the given response writer with methods to capture
// the status code, the number of bytes written, and methods to add new log
// entries. It won't wrap the response writer if it's already a
// ResponseLogger.
func NewResponseLogger(w http.ResponseWriter) ResponseLogger {
if rw, ok := w.(ResponseLogger); ok {
return rw
}
return wrapLogger(w)
}
func wrapLogger(w http.ResponseWriter) (rw ResponseLogger) {
rw = &rwDefault{w, 200, 0, nil}
if f, ok := w.(http.Flusher); ok {
rw = &rwFlusher{rw, f}
}
if h, ok := w.(http.Hijacker); ok {
rw = &rwHijacker{rw, h}
}
if p, ok := w.(http.Pusher); ok {
rw = &rwPusher{rw, p}
}
return
}
type rwDefault struct {
http.ResponseWriter
code int
size int
fields map[string]interface{}
}
func (r *rwDefault) Header() http.Header {
return r.ResponseWriter.Header()
}
func (r *rwDefault) Write(p []byte) (n int, err error) {
n, err = r.ResponseWriter.Write(p)
r.size += n
return
}
func (r *rwDefault) WriteHeader(code int) {
r.ResponseWriter.WriteHeader(code)
r.code = code
}
func (r *rwDefault) Size() int {
return r.size
}
func (r *rwDefault) StatusCode() int {
return r.code
}
func (r *rwDefault) Fields() map[string]interface{} {
return r.fields
}
func (r *rwDefault) WithFields(fields map[string]interface{}) {
if r.fields == nil {
r.fields = make(map[string]interface{}, len(fields))
}
for k, v := range fields {
r.fields[k] = v
}
}
type rwFlusher struct {
ResponseLogger
f http.Flusher
}
func (r *rwFlusher) Flush() {
r.f.Flush()
}
type rwHijacker struct {
ResponseLogger
h http.Hijacker
}
func (r *rwHijacker) Hijack() (net.Conn, *bufio.ReadWriter, error) {
return r.h.Hijack()
}
type rwPusher struct {
ResponseLogger
p http.Pusher
}
func (rw *rwPusher) Push(target string, opts *http.PushOptions) error {
return rw.p.Push(target, opts)
}