-
Notifications
You must be signed in to change notification settings - Fork 3
/
response_writers.go
78 lines (64 loc) · 1.93 KB
/
response_writers.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
// Thanks to https://github.com/authzed/prom-authzed-proxy/blob/main/cmd/prom-authzed-proxy/response_writers.go
// for the code
package main
import (
"bytes"
"net/http"
)
// filteredWriter wraps an http.ResponseWriter and resetting the values of any
// reserved headers.
type filteredWriter struct {
savedHeaders map[string][]string
http.ResponseWriter
}
// Compile-time assert that filteredWriter implements http.ResponseWriter.
var _ http.ResponseWriter = (*filteredWriter)(nil)
func newFilteredWriter(w http.ResponseWriter, reservedResponseHeaders ...string) *filteredWriter {
savedHeaders := make(map[string][]string, len(reservedResponseHeaders))
for _, name := range reservedResponseHeaders {
savedHeaders[name] = w.Header().Values(name)
}
return &filteredWriter{
ResponseWriter: w,
savedHeaders: savedHeaders,
}
}
func (w filteredWriter) resetHeaders() {
for name := range w.savedHeaders {
w.ResponseWriter.Header().Del(name)
for _, value := range w.savedHeaders[name] {
w.ResponseWriter.Header().Add(name, value)
}
}
}
func (w filteredWriter) WriteHeader(code int) {
w.resetHeaders()
w.ResponseWriter.WriteHeader(code)
}
func (w filteredWriter) Write(b []byte) (int, error) {
w.resetHeaders()
return w.ResponseWriter.Write(b)
}
// logWriter wraps an http.ResponseWriter and logs the request and response
// metadata.
type logWriter struct {
status int
body *bytes.Buffer
http.ResponseWriter
}
// Compile-time assert that logWriter implements http.ResponseWriter.
var _ http.ResponseWriter = (*logWriter)(nil)
func (w *logWriter) WriteHeader(statusCode int) {
w.status = statusCode
w.ResponseWriter.WriteHeader(statusCode)
}
func (w *logWriter) Write(b []byte) (int, error) {
w.body = bytes.NewBuffer(b)
return w.ResponseWriter.Write(b)
}
func logHandler(fn http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
lw := &logWriter{0, nil, w}
fn.ServeHTTP(lw, r)
})
}