-
Notifications
You must be signed in to change notification settings - Fork 0
/
curl.go
109 lines (95 loc) · 1.85 KB
/
curl.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
package curl
import (
"bytes"
"encoding/json"
"errors"
"io"
"io/ioutil"
"net/http"
"net/url"
)
var (
ErrInvalidResponse = errors.New("the response is invalid")
)
// Request ...
type CURL struct {
Request *http.Request
Response *http.Response
Error error
}
func (c *CURL) SetURLQuery(value url.Values) *CURL {
if c.Error != nil {
return c
}
c.Request.URL.RawQuery = value.Encode()
return c
}
// SetHeader ...
func (c *CURL) SetHeader(key, value string) *CURL {
if c.Error != nil {
return c
}
c.Request.Header.Set(key, value)
return c
}
// SetHeaderList ...
func (c *CURL) SetHeaderList(vstr ...string) *CURL {
if c.Error != nil {
return c
}
n := len(vstr)
for i := 0; i < n; i += 2 {
c.Request.Header.Set(vstr[i], vstr[i+1])
}
return c
}
// Send ...
func (c *CURL) Send() *CURL {
if c.Error != nil {
return c
}
c.Response, c.Error = http.DefaultClient.Do(c.Request)
return c
}
// ReadBytes ...
func (c *CURL) ReadBytes() ([]byte, error) {
if c.Error != nil {
return nil, c.Error
}
if c.Response == nil {
return nil, ErrInvalidResponse
}
data, err := ioutil.ReadAll(c.Response.Body)
if err != nil {
return nil, err
}
return data, nil
}
// ReadJSON ...
func (c *CURL) ReadJSON(x interface{}) error {
return json.NewDecoder(c.Response.Body).Decode(x)
}
// New ...
func New(method, url string, body io.Reader) *CURL {
req, err := http.NewRequest(method, url, body)
return &CURL{
Request: req,
Error: err,
}
}
// Post ...
func Post(url string, body io.Reader) *CURL {
return New(http.MethodPost, url, body)
}
// PostJSON ...
func PostJSON(url string, x interface{}) *CURL {
data, err := json.Marshal(x)
if err != nil {
return &CURL{Error: err}
}
return Post(url, bytes.NewBuffer(data)).SetHeader("Content-Type", "application/json")
}
// Get ...
func Get(url string) *CURL {
return New(http.MethodGet, url, nil)
}