-
Notifications
You must be signed in to change notification settings - Fork 1
/
request.go
55 lines (45 loc) · 1.08 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
package eclair
import (
"fmt"
"io"
"net/http"
"strings"
)
func (c *Client) Get(path string, response interface{}) ([]byte, error) {
return c.Request(http.MethodGet, path, nil, response)
}
func (c *Client) Post(path string, data io.Reader, response interface{}) ([]byte, error) {
return c.Request(http.MethodPost, path, data, response)
}
func (c *Client) Request(method, path string, data io.Reader, response interface{}) ([]byte, error) {
path = strings.TrimPrefix(path, "/")
url := strings.TrimSuffix(c.BaseURL, "/") + "/" + path
req, err := http.NewRequest(
method,
url,
data,
)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
if c.settings.Credentials != nil {
req.SetBasicAuth(
c.settings.Credentials.User,
c.settings.Credentials.Password,
)
}
resp, err := c.HTTPClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
d, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf(string(d))
}
return d, nil
}