-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathclient.go
102 lines (85 loc) · 2.04 KB
/
client.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
package uexchange
import (
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strings"
)
// NewClient - ..
func NewClient() *Client {
return &Client{}
}
func (c *Client) getAPIURL(endpoint string) string {
return apiHost + ":" + apiPort + "/" + endpoint
}
func (c *Client) sendRequest(requestURL string, requestType string, params url.Values) ([]byte, error) {
switch requestType {
default:
return nil, errors.New("invalid request type given: " + requestType)
case "POST":
return c.sendPOSTRequest(requestURL, params)
case "GET":
return c.sendGETRequest(requestURL, params)
}
}
func (c *Client) sendGETRequest(requestURL string, params url.Values) ([]byte, error) {
// declare http client
httpClient := &http.Client{}
// create request
urlWithParams := requestURL + "?" + params.Encode()
req, err := http.NewRequest(requestTypeGET, urlWithParams, nil)
if err != nil {
return nil, err
}
// set cookie
if c.AuthToken != "" {
req.AddCookie(&http.Cookie{
Name: "auth_token",
Value: c.AuthToken,
})
}
// send request
resp, err := httpClient.Do(req)
if err != nil {
return nil, err
}
// read response
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("read response: %s", err)
}
defer resp.Body.Close()
return body, nil
}
func (c *Client) sendPOSTRequest(requestURL string, params url.Values) ([]byte, error) {
// declare http client
httpClient := &http.Client{}
// create request
req, err := http.NewRequest(requestTypePOST, requestURL, strings.NewReader(params.Encode()))
if err != nil {
return nil, fmt.Errorf("send request: %w", err)
}
// set cookie
if c.AuthToken != "" {
req.AddCookie(&http.Cookie{
Name: "auth_token",
Value: c.AuthToken,
})
}
// set headers
req.Header.Set(headerContentType, apiRequestContentType)
// send request
resp, err := httpClient.Do(req)
if err != nil {
return nil, err
}
// read response
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("read response: %s", err)
}
defer resp.Body.Close()
return body, nil
}