-
Notifications
You must be signed in to change notification settings - Fork 0
/
simplehttp.go
104 lines (81 loc) · 1.71 KB
/
simplehttp.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
package simplehttp
import (
"bytes"
"io"
"net/http"
)
type HttpReqest struct {
method string
url string
headers http.Header
cookie []*http.Cookie
body io.Reader
}
var globalClient = &http.Client{}
func CustomClient(client *http.Client) {
if client != nil {
globalClient = client
}
}
func CreateHttpRequest(url string) HttpReqest {
return HttpReqest{
method: http.MethodGet,
body: nil,
url: url,
headers: make(http.Header),
}
}
func (h *HttpReqest) Url(u string) *HttpReqest {
h.url = u
return h
}
func (h *HttpReqest) Get() *HttpReqest {
return h.SetMethod(http.MethodGet)
}
func (h *HttpReqest) Post() *HttpReqest {
return h.SetMethod(http.MethodPost)
}
func (h *HttpReqest) Put() *HttpReqest {
return h.SetMethod(http.MethodPut)
}
func (h *HttpReqest) Delete() *HttpReqest {
return h.SetMethod(http.MethodDelete)
}
func (h *HttpReqest) SetMethod(method string) *HttpReqest {
h.method = method
return h
}
func (h *HttpReqest) Body(body []byte) *HttpReqest {
h.body = bytes.NewReader(body)
return h
}
func (h *HttpReqest) AddCookie(cookie *http.Cookie) *HttpReqest {
h.cookie = append(h.cookie, cookie)
return h
}
func (h *HttpReqest) AddHeader(key, value string) *HttpReqest {
h.headers.Add(key, value)
return h
}
func (h *HttpReqest) Execute() (*http.Response, error) {
return h.ExecuteWithClient(*globalClient)
}
func (h *HttpReqest) ExecuteWithClient(client http.Client) (*http.Response, error) {
req, err := http.NewRequest(
h.method,
h.url,
h.body,
)
if err != nil {
return nil, err
}
req.Header = h.headers
for _, cookie := range h.cookie {
req.AddCookie(cookie)
}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
return resp, nil
}