forked from motemen/go-loghttp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
loghttp.go
69 lines (56 loc) · 1.59 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
// Package loghttp provides automatic logging functionalities to http.Client.
package loghttp
import (
"log"
"net/http"
)
// 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) {
log.Printf("<--- %d %s", resp.StatusCode, resp.Request.URL)
}
// 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) {
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
}