-
Notifications
You must be signed in to change notification settings - Fork 0
/
roundtripper.go
45 lines (36 loc) · 895 Bytes
/
roundtripper.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
package logtransport
import (
"fmt"
"io"
"net/http"
)
type logRoundTripper struct {
http.RoundTripper
logOutput io.Writer
opts *Opts
}
func (l *logRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
fmt.Fprintln(l.logOutput, ">", req.Method, req.Proto, req.RequestURI)
if l.opts.LogReqHeaders {
for k, v := range req.Header {
fmt.Fprintln(l.logOutput, ">", k+":", v)
}
}
if l.opts.LogReqBody {
req.Body = newReadCloser("> Request Body:\n\n", l.logOutput, req.Body)
}
resp, err := l.RoundTripper.RoundTrip(req)
if err != nil {
return resp, err
}
fmt.Fprintln(l.logOutput, "<", resp.Proto, resp.Status)
if l.opts.LogRespHeaders {
for k, v := range resp.Header {
fmt.Fprintln(l.logOutput, "<", k+":", v)
}
}
if l.opts.LogRespBody {
resp.Body = newReadCloser("< Response Body:\n\n", l.logOutput, resp.Body)
}
return resp, nil
}