-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathround_tripper.go
301 lines (264 loc) · 6.47 KB
/
round_tripper.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
package harlog
import (
"bytes"
"encoding/base64"
"io/ioutil"
"log"
"mime"
"net/http"
"net/http/httptrace"
"strings"
"sync"
)
var _ http.RoundTripper = (*Transport)(nil)
// Transport is collecting http request/response log by HAR format.
type Transport struct {
// next Transport. if nil, use http.DefaultTransport.
Transport http.RoundTripper
// unusual (not network oriented) error occurred, handle error by this function.
// if nil, emit error log by log package, and ignore it.
UnusualError func(err error) error
har *HARContainer
mutex sync.Mutex
}
func (h *Transport) init() {
if h.har != nil {
return
}
h.mutex.Lock()
defer h.mutex.Unlock()
if h.har != nil {
return
}
h.har = &HARContainer{
Log: &Log{
Version: "1.2",
Creator: &Creator{
Name: "github.com/vvakame/go-harlog",
Version: "0.0.1",
},
},
}
}
// HAR returns HAR format log data.
func (h *Transport) HAR() *HARContainer {
h.init()
return h.har
}
// RoundTrip executes a single HTTP transaction, returning
// a Response for the provided Request.
func (h *Transport) RoundTrip(r *http.Request) (*http.Response, error) {
h.init()
baseRoundTripper := h.Transport
if baseRoundTripper == nil {
baseRoundTripper = http.DefaultTransport
}
entry := &Entry{}
defer func() {
h.mutex.Lock()
h.har.Log.Entries = append(h.har.Log.Entries, entry)
h.mutex.Unlock()
}()
err := h.preRoundTrip(r, entry)
if err != nil {
if h.UnusualError != nil {
err = h.UnusualError(err)
} else {
log.Println(err)
err = nil
}
if err != nil {
return nil, err
}
}
trace, ct, finish := newClientTracer()
r = r.WithContext(httptrace.WithClientTrace(r.Context(), ct))
defer func() {
entry.StartedDateTime = Time(trace.startAt)
entry.Time = Duration(trace.endAt.Sub(trace.startAt))
entry.Timings = &Timings{
Blocked: Duration(trace.startAt.Sub(trace.connStart)),
DNS: -1,
Connect: -1,
Send: Duration(trace.writeRequest.Sub(trace.connObtained)),
Wait: Duration(trace.firstResponseByte.Sub(trace.writeRequest)),
Receive: Duration(trace.endAt.Sub(trace.firstResponseByte)),
SSL: -1,
}
if !trace.dnsStart.IsZero() {
entry.Timings.DNS = Duration(trace.dnsEnd.Sub(trace.dnsStart))
}
if !trace.connStart.IsZero() {
entry.Timings.Connect = Duration(trace.connObtained.Sub(trace.connStart))
}
if !trace.tlsHandshakeStart.IsZero() {
entry.Timings.SSL = Duration(trace.tlsHandshakeEnd.Sub(trace.tlsHandshakeStart))
}
}()
resp, realErr := baseRoundTripper.RoundTrip(r)
err = h.postRoundTrip(r, resp, entry, finish)
if err != nil {
if h.UnusualError != nil {
err = h.UnusualError(err)
} else {
log.Println(err)
err = nil
}
if err != nil {
return nil, err
}
}
entry.Cache = &Cache{}
return resp, realErr
}
func (h *Transport) preRoundTrip(r *http.Request, entry *Entry) error {
bodySize := -1
var postData *PostData
if r.Body != nil {
reqBody, err := r.GetBody()
if err != nil {
return err
}
reqBodyBytes, err := ioutil.ReadAll(reqBody)
if err != nil {
return err
}
bodySize = len(reqBodyBytes)
mimeType := r.Header.Get("Content-Type")
postData = &PostData{
MimeType: mimeType,
Params: []*Param{},
Text: string(reqBodyBytes),
}
mediaType, _, err := mime.ParseMediaType(mimeType)
if err != nil {
return err
}
switch mediaType {
case "application/x-www-form-urlencoded":
err := r.ParseForm()
if err != nil {
return err
}
r.Body = ioutil.NopCloser(bytes.NewBuffer(reqBodyBytes))
for k, v := range r.PostForm {
for _, s := range v {
postData.Params = append(postData.Params, &Param{
Name: k,
Value: s,
})
}
}
case "multipart/form-data":
err := r.ParseMultipartForm(10 * 1024 * 1024)
if err != nil {
return err
}
r.Body = ioutil.NopCloser(bytes.NewBuffer(reqBodyBytes))
for k, v := range r.MultipartForm.Value {
for _, s := range v {
postData.Params = append(postData.Params, &Param{
Name: k,
Value: s,
})
}
}
for k, v := range r.MultipartForm.File {
for _, s := range v {
postData.Params = append(postData.Params, &Param{
Name: k,
FileName: s.Filename,
ContentType: s.Header.Get("Content-Type"),
})
}
}
}
}
entry.Request = &Request{
Method: r.Method,
URL: r.URL.String(),
HTTPVersion: r.Proto,
Cookies: h.toHARCookies(r.Cookies()),
Headers: h.toHARNVP(r.Header),
QueryString: h.toHARNVP(r.URL.Query()),
PostData: postData,
HeadersSize: -1, // TODO
BodySize: bodySize,
}
return nil
}
func (h *Transport) postRoundTrip(r *http.Request, resp *http.Response, entry *Entry, finish func()) error {
if resp == nil {
finish()
return nil
}
respBody := resp.Body
respBodyBytes, err := ioutil.ReadAll(respBody)
defer func() {
_ = respBody.Close()
}()
finish() // データ読み終わった瞬間が終わり
if err != nil {
return err
}
resp.Body = ioutil.NopCloser(bytes.NewBuffer(respBodyBytes))
mimeType := resp.Header.Get("Content-Type")
mediaType, _, err := mime.ParseMediaType(mimeType)
if err != nil {
return err
}
var text string
var encoding string
switch {
case strings.HasPrefix(mediaType, "text/"):
text = string(respBodyBytes)
default:
text = base64.StdEncoding.EncodeToString(respBodyBytes)
encoding = "base64"
}
entry.Response = &Response{
Status: resp.StatusCode,
StatusText: "",
HTTPVersion: resp.Proto,
Cookies: h.toHARCookies(resp.Cookies()),
Headers: h.toHARNVP(resp.Header),
Content: &Content{
Size: resp.ContentLength, // TODO 圧縮されている場合のフォロー
Compression: 0,
MimeType: mimeType,
Text: text,
Encoding: encoding,
},
RedirectURL: resp.Header.Get("Location"),
HeadersSize: -1,
BodySize: resp.ContentLength,
}
return nil
}
func (h *Transport) toHARCookies(cookies []*http.Cookie) []*Cookie {
harCookies := make([]*Cookie, 0, len(cookies))
for _, cookie := range cookies {
harCookies = append(harCookies, &Cookie{
Name: cookie.Name,
Value: cookie.Value,
Path: cookie.Path,
Domain: cookie.Domain,
Expires: Time(cookie.Expires),
HTTPOnly: cookie.HttpOnly,
Secure: cookie.Secure,
})
}
return harCookies
}
func (h *Transport) toHARNVP(vs map[string][]string) []*NVP {
nvps := make([]*NVP, 0, len(vs))
for k, v := range vs {
for _, s := range v {
nvps = append(nvps, &NVP{
Name: k,
Value: s,
})
}
}
return nvps
}