-
Notifications
You must be signed in to change notification settings - Fork 64
Expand file tree
/
Copy pathhttp_client.go
More file actions
119 lines (103 loc) · 2.35 KB
/
http_client.go
File metadata and controls
119 lines (103 loc) · 2.35 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
package network
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"time"
)
type Client struct {
httpClient *http.Client
}
type Response struct {
StatusCode int
Body []byte
Header http.Header
}
func NewHTTPClient(timeout time.Duration) *http.Client {
return &http.Client{
Timeout: timeout,
CheckRedirect: func(req *http.Request, via []*http.Request) error {
if len(via) == 0 {
return nil
}
if req.URL.Host != via[0].URL.Host {
return http.ErrUseLastResponse
}
return nil
},
}
}
func NewClient(timeout time.Duration) *Client {
return &Client{
httpClient: NewHTTPClient(timeout),
}
}
func (c *Client) DoJSON(method, url string, payload any, bearerToken, orgContext string, headers map[string]string) (*Response, error) {
var bodyReader io.Reader
if payload != nil {
bodyJSON, err := json.Marshal(payload)
if err != nil {
return nil, fmt.Errorf("failed to marshal request: %w", err)
}
bodyReader = bytes.NewReader(bodyJSON)
}
req, err := http.NewRequest(method, url, bodyReader)
if err != nil {
return nil, err
}
if payload != nil {
req.Header.Set("Content-Type", "application/json")
}
if bearerToken != "" {
req.Header.Set("Authorization", "Bearer "+bearerToken)
}
if orgContext != "" {
req.Header.Set("X-Org-Context", orgContext)
}
for key, value := range headers {
req.Header.Set(key, value)
}
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read response body: %w", err)
}
return &Response{
StatusCode: resp.StatusCode,
Body: body,
Header: resp.Header,
}, nil
}
func (c *Client) Do(method, url string, body []byte, headers map[string]string) (*Response, error) {
var bodyReader io.Reader
if body != nil {
bodyReader = bytes.NewReader(body)
}
req, err := http.NewRequest(method, url, bodyReader)
if err != nil {
return nil, err
}
for key, value := range headers {
req.Header.Set(key, value)
}
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read response body: %w", err)
}
return &Response{
StatusCode: resp.StatusCode,
Body: respBody,
Header: resp.Header,
}, nil
}