Repository navigation
Expand file tree
/
Copy pathhttp.go
More file actions
139 lines (118 loc) · 3.33 KB
/
Copy pathhttp.go
File metadata and controls
139 lines (118 loc) · 3.33 KB
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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
package decodo
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
)
type authType int
const (
authTypeBasic authType = iota
authTypeBearer
)
type httpClientConfig struct {
baseURL string
authType authType
credential string
timeoutMs int
integrationHeader string
}
type httpClient struct {
config httpClientConfig
client *http.Client
}
func newHTTPClient(config httpClientConfig) *httpClient {
transport := &http.Transport{
MaxIdleConns: 100,
IdleConnTimeout: 90 * time.Second,
}
return &httpClient{
config: config,
client: &http.Client{Transport: transport},
}
}
type errorResponse struct {
Status string `json:"status"`
Message string `json:"message"`
Error string `json:"error"`
Errors []interface{} `json:"errors"`
}
func (c *httpClient) request(ctx context.Context, method, path string, body interface{}) ([]byte, error) {
reqURL := strings.TrimRight(c.config.baseURL, "/") + path
var bodyReader io.Reader
if body != nil {
data, err := json.Marshal(body)
if err != nil {
return nil, fmt.Errorf("marshaling request body: %w", err)
}
bodyReader = bytes.NewReader(data)
}
timeoutCtx, cancel := context.WithTimeout(ctx, time.Duration(c.config.timeoutMs)*time.Millisecond)
defer cancel()
req, err := http.NewRequestWithContext(timeoutCtx, method, reqURL, bodyReader)
if err != nil {
return nil, fmt.Errorf("creating request: %w", err)
}
switch c.config.authType {
case authTypeBasic:
req.Header.Set("Authorization", "Basic "+c.config.credential)
case authTypeBearer:
req.Header.Set("Authorization", "Bearer "+c.config.credential)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
req.Header.Set("x-integration", c.config.integrationHeader)
resp, err := c.client.Do(req)
if err != nil {
if timeoutCtx.Err() == context.DeadlineExceeded && ctx.Err() == nil {
return nil, &TimeoutError{Msg: fmt.Sprintf("request to %s timed out after %dms", path, c.config.timeoutMs)}
}
if ctx.Err() == context.Canceled {
return nil, &CancellationError{Msg: fmt.Sprintf("request to %s was cancelled", path)}
}
return nil, fmt.Errorf("executing request: %w", err)
}
defer resp.Body.Close()
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("reading response body: %w", err)
}
if resp.StatusCode == 204 {
return nil, nil
}
if resp.StatusCode >= 200 && resp.StatusCode < 300 {
return respBody, nil
}
var errResp errorResponse
_ = json.Unmarshal(respBody, &errResp)
message := errResp.Message
if message == "" {
message = errResp.Error
}
if message == "" {
message = fmt.Sprintf("HTTP %d", resp.StatusCode)
}
return nil, mapHTTPError(resp.StatusCode, message, errResp.Status, errResp.Errors)
}
func (c *httpClient) post(ctx context.Context, path string, body interface{}) ([]byte, error) {
return c.request(ctx, http.MethodPost, path, body)
}
func (c *httpClient) get(ctx context.Context, path string, query map[string]string) ([]byte, error) {
if len(query) > 0 {
params := url.Values{}
for k, v := range query {
params.Set(k, v)
}
if strings.Contains(path, "?") {
path = path + "&" + params.Encode()
} else {
path = path + "?" + params.Encode()
}
}
return c.request(ctx, http.MethodGet, path, nil)
}