forked from txthinking/frank
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttp.go
52 lines (48 loc) · 907 Bytes
/
http.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
package main
import (
"bytes"
"io"
"net/http"
"time"
)
// HttpClient is a http client
type HttpClient struct {
Client *http.Client
URL string
}
// NewHttpClient return a new client
func NewHttpClient(url string) *HttpClient {
c := &HttpClient{
Client: &http.Client{
Timeout: 10 * time.Second,
},
URL: url,
}
return c
}
// Do a request
func (c *HttpClient) Do(req *Request) (*http.Response, error) {
var body io.Reader
if req.Method == "POST" || req.Method == "PUT" || req.Method == "PATCH" {
body = bytes.NewReader(req.Body)
}
q := "?" + req.Query.Encode()
if q == "?" {
q = ""
}
r, err := http.NewRequest(req.Method, c.URL+req.Path+q, body)
if err != nil {
return nil, err
}
r.Header = req.Header
res, err := c.Client.Do(r)
if err != nil {
return nil, err
}
if !markdown {
PrintRequest(r, req)
} else {
PrintRequestMarkdown(r, req)
}
return res, nil
}