-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrequest.go
124 lines (105 loc) · 2.21 KB
/
request.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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
package scripts
import (
"encoding/json"
"io"
"net/http"
"net/url"
"strings"
)
type Request struct {
Method string
URL string
Header map[string]string
Query map[string]string
Body interface{}
Object *interface{}
}
func (r *Request) Do() error {
client := &http.Client{}
// build query
query := url.Values{}
for key, value := range r.Query {
query.Set(key, value)
}
var req *http.Request
// build request
if r.Body != nil {
jsonData, err := json.Marshal(r.Body)
if err != nil {
return err
}
req, err = http.NewRequest(r.Method, r.URL, strings.NewReader(string(jsonData)))
if err != nil {
return err
}
} else {
var err error
req, err = http.NewRequest(r.Method, r.URL, strings.NewReader(query.Encode()))
if err != nil {
return err
}
}
// set headers to request
for key, value := range r.Header {
req.Header.Set(key, value)
}
// do request
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
// read response body
body, err := io.ReadAll(resp.Body)
if err != nil {
return err
}
// unmarshal response body to object
err = json.Unmarshal(body, r.Object)
if err != nil {
return err
}
return nil
}
func newRequest(url string) *Request {
req := &Request{Header: make(map[string]string), Query: make(map[string]string)}
req.URL = url
return req
}
func Get(url string) *Request {
req := newRequest(url)
req.Method = "GET"
return req
}
func Post(url string) *Request {
req := newRequest(url)
req.Method = "POST"
return req
}
func (req *Request) WithHeader(key, value string) *Request {
req.Header[key] = value
return req
}
func (req *Request) WithQuery(key, value string) *Request {
req.Query[key] = value
return req
}
func (req *Request) WithObject(object interface{}) *Request {
req.Object = &object
return req
}
func (req *Request) WithBody(body interface{}) *Request {
req.Body = body
return req
}
// type JSON map[string]string
//
// header := JSON{
// "Content-Type": "application/x-www-form-urlencoded",
// "Authorization": "Basic " + idAndSecret,
// }
// query := JSON{
// "grant_type": "authorization_code",
// "code": c.QueryParam("code"),
// "redirect_uri": "http://localhost:3000/callback",
// }