forked from fulldump/apitest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
request.go
127 lines (92 loc) · 2.05 KB
/
request.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
package apitest
import (
"bytes"
"encoding/json"
"io"
"io/ioutil"
"net/http"
"strings"
)
type Request struct {
http.Request
apitest *Apitest
client *http.Client
}
func NewRequest(method, urlStr string, a *Apitest) *Request {
http_request, err := http.NewRequest(method, urlStr, strings.NewReader(""))
if nil != err {
panic(err)
}
return &Request{*http_request, a, a.client}
}
func (r *Request) WithCredentials(api_key, api_secret string) *Request {
r.Header.Set("Api-Key", api_key)
r.Header.Set("Api-Secret", api_secret)
return r
}
func (r *Request) WithCookie(key, value string) *Request {
c := &http.Cookie{
Name: key,
Value: value,
}
r.AddCookie(c)
return r
}
func (r *Request) set_body(body io.Reader) {
rc, ok := body.(io.ReadCloser)
if !ok && body != nil {
rc = ioutil.NopCloser(body)
}
r.Body = rc
if body != nil {
switch v := body.(type) {
case *bytes.Buffer:
r.ContentLength = int64(v.Len())
case *bytes.Reader:
r.ContentLength = int64(v.Len())
case *strings.Reader:
r.ContentLength = int64(v.Len())
}
}
}
func (r *Request) WithHeader(key, value string) *Request {
r.Header.Set(key, value)
return r
}
func (r *Request) WithBodyString(body string) *Request {
b := strings.NewReader(body)
r.set_body(b)
return r
}
func (r *Request) WithBodyJson(o interface{}) *Request {
bytes, err := json.Marshal(o)
if nil != err {
panic(err)
}
r.WithBodyString(string(bytes))
return r
}
func (r *Request) WithHttpClient(client *http.Client) *Request {
r.client = client
return r
}
func (r *Request) Do() *Response {
tee := &tee{Buffer: r.Request.Body}
r.Request.Body = tee
res, err := r.client.Do(&r.Request)
if err != nil {
panic(err)
}
return &Response{Response: *res, response_body_bytes: nil, request_body_bytes: tee.Bytes}
}
func (r *Request) DoAsync(f func(*Response)) {
c := <-r.apitest.clients
response, err := c.Do(&r.Request)
if err != nil {
panic(err)
}
wresponse := &Response{*response, r.apitest, c, nil, nil}
f(wresponse)
wresponse.BodyClose()
r.apitest.clients <- c
}