-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathdebug.go
More file actions
43 lines (38 loc) · 840 Bytes
/
Copy pathdebug.go
File metadata and controls
43 lines (38 loc) · 840 Bytes
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
package gohttp
import (
"bytes"
"io"
"net/http"
"net/http/httputil"
"regexp"
)
type debugger struct {
rt http.RoundTripper
w io.Writer
reqBody bool
respBody bool
}
func (t *debugger) RoundTrip(req *http.Request) (*http.Response, error) {
if t.rt == nil {
t.rt = http.DefaultTransport
}
reqBody, err := httputil.DumpRequestOut(req, t.reqBody)
if err != nil {
return nil, err
}
t.Write("-> ", reqBody)
res, err := t.rt.RoundTrip(req)
if err != nil {
return nil, err
}
respBody, err := httputil.DumpResponse(res, t.respBody)
if err != nil {
return nil, err
}
t.Write("<- ", respBody)
return res, nil
}
var lineStart = regexp.MustCompile(`(?m)^`)
func (w *debugger) Write(prefix string, buf []byte) {
w.w.Write(append(lineStart.ReplaceAll(bytes.TrimSpace(buf), []byte(prefix)), '\n', '\n'))
}