This repository has been archived by the owner on Oct 24, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathtransaction.go
94 lines (80 loc) · 1.75 KB
/
transaction.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
package transaction
import (
"bytes"
"compress/gzip"
"io"
"io/ioutil"
"net/http"
"net/url"
"time"
"github.com/google/uuid"
)
type Req struct {
URL *url.URL `json:"URL"`
Method string `json:"Method"`
Proto string `json:"Proto"`
Header http.Header `json:"Header"`
Body []byte `json:"Body"`
}
type Resp struct {
Proto string
Header http.Header `json:"Header"`
Body []byte `json:"Body"`
Status string `json:"Status"`
}
type Tx struct {
ID uuid.UUID `json:"ID"`
Req *Req `json:"Req"`
Resp *Resp `json:"Resp"`
ClientAddr string `json:"ClientAddr"`
BeginAt time.Time `json:"BeginAt"`
EndAt time.Time `json:"EndAt"`
}
func NewReq(req *http.Request) *Req {
rURL := new(url.URL)
rawReqURL := req.Context().Value("rawRequestURL")
if rawReqURL != nil {
*rURL = *rawReqURL.(*url.URL)
} else {
*rURL = *req.URL
}
var body []byte
req.Body, body = copyBody(req.Body)
return &Req{
URL: rURL,
Method: req.Method,
Proto: req.Proto,
Header: CopyHeader(req.Header),
Body: body,
}
}
func NewResp(resp *http.Response) *Resp {
var body []byte
resp.Body, body = copyBody(resp.Body)
switch resp.Header.Get("Content-Encoding") {
case "gzip":
g, _ := gzip.NewReader(bytes.NewReader(body))
body, _ = ioutil.ReadAll(g)
}
return &Resp{
Proto: resp.Proto,
Header: CopyHeader(resp.Header),
Body: body,
Status: resp.Status,
}
}
func CopyHeader(h http.Header) http.Header {
header := make(http.Header)
for k, v := range h {
header[k] = v
}
return header
}
func copyBody(r io.ReadCloser) (io.ReadCloser, []byte) {
body := make([]byte, 0)
if r != nil {
body, _ = ioutil.ReadAll(r)
r = ioutil.NopCloser(bytes.NewReader(body))
}
return r, body
}