-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdump.go
More file actions
79 lines (64 loc) · 1.92 KB
/
Copy pathdump.go
File metadata and controls
79 lines (64 loc) · 1.92 KB
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
package httptestutil
import (
"bytes"
"fmt"
"io"
"net/http"
"net/http/httptest"
"net/http/httputil"
"os"
"github.com/felixge/httpsnoop"
)
// DumpTo wraps an http.Handler in a new handler
// the new handler dumps requests and responses to a writer, using the httputil.DumpRequest and
// httputil.DumpResponse functions
func DumpTo(handler http.Handler, writer io.Writer) http.Handler {
// use the same default as http.Server
if handler == nil {
handler = http.DefaultServeMux
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
dump, err := httputil.DumpRequest(r, true)
if err != nil {
_, _ = fmt.Fprintf(writer, "error dumping request: %#v", err)
} else {
_, _ = writer.Write(append(dump, []byte("\r\n")...))
}
ex := Exchange{}
w = httpsnoop.Wrap(w, hooks(&ex))
handler.ServeHTTP(w, r)
resp := http.Response{
Proto: r.Proto,
ProtoMajor: r.ProtoMajor,
ProtoMinor: r.ProtoMinor,
StatusCode: ex.StatusCode,
Header: w.Header(),
Body: io.NopCloser(bytes.NewReader(ex.ResponseBody.Bytes())),
ContentLength: int64(ex.ResponseBody.Len()),
}
d, err := httputil.DumpResponse(&resp, true)
if err != nil {
fmt.Fprintf(writer, "error dumping response: %#v", err) // nolint: errcheck
} else {
writer.Write(append(d, []byte("\r\n")...)) // nolint: errcheck
}
})
}
// Dump writes requests and responses to the writer
func Dump(ts *httptest.Server, to io.Writer) {
ts.Config.Handler = DumpTo(ts.Config.Handler, to)
}
// DumpToStdout writes requests and responses to os.Stdout
func DumpToStdout(ts *httptest.Server) {
Dump(ts, os.Stdout)
}
type logFunc func(a ...any)
// Write implements io.Writer
func (f logFunc) Write(p []byte) (n int, err error) {
f(string(p))
return len(p), nil
}
// DumpToLog writes requests and responses to a logging function
func DumpToLog(ts *httptest.Server, logf func(a ...any)) {
Dump(ts, logFunc(logf))
}