/
send.go
58 lines (47 loc) · 1.37 KB
/
send.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
package client
import (
"io/ioutil"
"net/http"
"time"
"github.com/ddo/rq"
)
// Send sends the request and read it if read is true
// remember to close the res.Body if read is false
// Send also set content-type to application/x-www-form-urlencoded
// if form is available
func (c *Client) Send(r *rq.Rq, read bool) (data []byte, res *http.Response, err error) {
// apply defaultRq
newRq := ApplyDefaultRq(c.defaultRq, r)
req, err := newRq.ParseRequest()
if err != nil {
log.Error(err)
return
}
// set content type for form
if req.Header.Get("content-type") == "" && len(newRq.Form) > 0 && newRq.Body == nil {
req.Header.Set("content-type", "application/x-www-form-urlencoded")
}
if req.Header.Get("user-agent") == "" {
req.Header.Set("user-agent", defaultUserAgent)
}
log.Info(req.Method, "\t>", req.URL.String())
now := time.Now()
res, err = c.httpClient.Do(req)
if err != nil {
log.Error("HTTP\t<", err, humanizeNano(time.Now().Sub(now)))
return
}
log.Info(res.StatusCode, "\t<", res.Request.URL, humanizeNano(time.Now().Sub(now)))
// stop here if read is false
if !read {
return
}
// read the response
defer res.Body.Close()
data, err = ioutil.ReadAll(res.Body)
return
}
// Send is the wrapper of #Send but use the default client
func Send(r *rq.Rq, read bool) (data []byte, res *http.Response, err error) {
return DefaultClient.Send(r, read)
}