forked from motemen/go-loghttp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
loghttp.go
87 lines (70 loc) · 2.07 KB
/
loghttp.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
79
80
81
82
83
84
85
86
87
// Package loghttp provides automatic logging functionalities to http.Client.
package loghttp
import (
"context"
"log"
"net/http"
"time"
"github.com/64mb/go-nuts/roundtime"
)
// Transport implements http.RoundTripper. When set as Transport of http.Client, it executes HTTP requests with logging.
// No field is mandatory.
type Transport struct {
Transport http.RoundTripper
LogRequest func(req *http.Request)
LogResponse func(resp *http.Response)
}
// THe default logging transport that wraps http.DefaultTransport.
var DefaultTransport = &Transport{
Transport: http.DefaultTransport,
}
// Used if transport.LogRequest is not set.
var DefaultLogRequest = func(req *http.Request) {
log.Printf("--> %s %s", req.Method, req.URL)
}
// Used if transport.LogResponse is not set.
var DefaultLogResponse = func(resp *http.Response) {
ctx := resp.Request.Context()
if start, ok := ctx.Value(ContextKeyRequestStart).(time.Time); ok {
log.Printf("<-- %d %s (%s)", resp.StatusCode, resp.Request.URL, roundtime.Duration(time.Now().Sub(start), 2))
} else {
log.Printf("<-- %d %s", resp.StatusCode, resp.Request.URL)
}
}
type contextKey struct {
name string
}
var ContextKeyRequestStart = &contextKey{"RequestStart"}
// RoundTrip is the core part of this module and implements http.RoundTripper.
// Executes HTTP request with request/response logging.
func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) {
ctx := context.WithValue(req.Context(), ContextKeyRequestStart, time.Now())
req = req.WithContext(ctx)
t.logRequest(req)
resp, err := t.transport().RoundTrip(req)
if err != nil {
return resp, err
}
t.logResponse(resp)
return resp, err
}
func (t *Transport) logRequest(req *http.Request) {
if t.LogRequest != nil {
t.LogRequest(req)
} else {
DefaultLogRequest(req)
}
}
func (t *Transport) logResponse(resp *http.Response) {
if t.LogResponse != nil {
t.LogResponse(resp)
} else {
DefaultLogResponse(resp)
}
}
func (t *Transport) transport() http.RoundTripper {
if t.Transport != nil {
return t.Transport
}
return http.DefaultTransport
}