-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
61 lines (47 loc) · 1.42 KB
/
main.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
package main
import (
"context"
"fmt"
"net/http"
"strings"
"time"
"github.com/dillonstreator/roundtriphook"
)
type rthCtxKey string
var (
timeStartKey = rthCtxKey("startTime")
idKey = rthCtxKey("id")
)
var loggingTransport = roundtriphook.NewTransport(
// This call to roundtriphook.WithBaseRoundTripper is unnecessary
// since the default behavior is to set the base round tripper to http.DefaultTransport if none is provided
roundtriphook.WithBaseRoundTripper(http.DefaultTransport),
roundtriphook.WithBefore(func(req *http.Request) *http.Request {
startTime := time.Now()
id := startTime.UnixNano()
fmt.Printf("[%d] -> %s %s\n", id, req.Method, req.URL)
ctx := req.Context()
ctx = context.WithValue(ctx, timeStartKey, startTime)
ctx = context.WithValue(ctx, idKey, id)
return req.WithContext(ctx)
}),
roundtriphook.WithAfter(func(req *http.Request, res *http.Response, err error) {
startTime := req.Context().Value(timeStartKey).(time.Time)
id := req.Context().Value(idKey).(int64)
sb := strings.Builder{}
sb.WriteString(fmt.Sprintf("[%d] <- %s %s %s", id, req.Method, req.URL, time.Since(startTime)))
if res != nil {
sb.WriteString(" " + res.Status)
}
if err != nil {
sb.WriteString(fmt.Sprintf(" %s", err.Error()))
}
fmt.Printf("%s\n", sb.String())
}),
)
func main() {
httpClient := &http.Client{
Transport: loggingTransport,
}
httpClient.Get("https://www.google.com")
}