-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathrequest.go
70 lines (58 loc) · 1.25 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
package apipgu
import (
"encoding/json"
"fmt"
"io"
"net/http"
)
func (c *Client) requestJSON(
method,
endpoint,
contentType,
accessToken string,
body io.Reader,
result any,
) error {
resBody, err := c.requestBody(method, endpoint, contentType, accessToken, body)
if err != nil {
return err
}
if err = json.Unmarshal(resBody, result); err != nil {
return fmt.Errorf("%w: %w", ErrJSONUnmarshal, err)
}
return nil
}
func (c *Client) requestBody(
method,
endpoint,
contentType,
accessToken string,
body io.Reader,
) ([]byte, error) {
req, err := http.NewRequest(method, c.baseURI+endpoint, body)
if err != nil {
return nil, fmt.Errorf("%w: %w", ErrRequest, err)
}
if contentType != "" {
req.Header.Set("Content-Type", contentType)
}
if accessToken != "" {
req.Header.Set("Authorization", "Bearer "+accessToken)
}
c.logReq(req)
res, err := c.httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("%w: %w", ErrRequest, err)
}
c.logRes(res)
if res.StatusCode >= 400 || res.StatusCode == http.StatusNoContent {
return nil, responseError(res)
}
//goland:noinspection ALL
defer res.Body.Close()
resBody, err := io.ReadAll(res.Body)
if err != nil {
return nil, fmt.Errorf("%w: %w", ErrRequest, err)
}
return resBody, nil
}