-
Notifications
You must be signed in to change notification settings - Fork 0
/
do.go
75 lines (61 loc) · 1.26 KB
/
do.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
package restreq
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
)
func (r *Request) do(method string) (*Response, error) {
var c httpClient
if r.client == nil {
c = &http.Client{
Timeout: r.timeout,
}
} else {
c = r.client
}
payload := &bytes.Buffer{}
if len(r.jsonPayload) > 0 {
payload.Write(r.jsonPayload)
} else {
if err := json.NewEncoder(payload).Encode(r.json); err != nil {
return nil, err
}
}
r.debug(ReqBody, fmt.Sprintf("Body: %s", strings.TrimRight(payload.String(), "\n")))
req, err := http.NewRequest(method, r.url, payload)
if err != nil {
return nil, err
}
if r.ctx != nil {
req = req.WithContext(r.ctx)
}
for k, v := range r.headers {
req.Header.Set(k, v)
r.debug(ReqHeaders, fmt.Sprintf("Header: %s: %s", k, v))
}
if r.username != "" && r.password != "" {
r.SetBasicAuth(r.username, r.password)
}
for k, v := range r.cookies {
r.AddCookie(v)
r.debug(ReqCookies, fmt.Sprintf("Cookie: %s: %s", k, v))
}
resp, err := c.Do(req)
if err != nil {
return nil, err
}
body := &bytes.Buffer{}
if !r.bodyReader {
if _, err = io.Copy(body, resp.Body); err != nil {
return nil, err
}
resp.Body.Close()
}
return &Response{
Response: resp,
Body: body.Bytes(),
}, nil
}