-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttp-json.go
54 lines (45 loc) · 977 Bytes
/
http-json.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
package main
import (
"bytes"
"context"
"encoding/json"
"io"
"net/http"
)
type Client struct {
client *http.Client
}
func NewClient(httpClient *http.Client) *Client {
return &Client{httpClient}
}
func (c *Client) DoRequest(ctx context.Context, method, url string, jsonData interface{}) ([]byte, error) {
req, err := createRequest(ctx, method, url, jsonData)
if err != nil {
return nil, err
}
resp, err := c.client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
bb, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return bb, nil
}
func createRequest(ctx context.Context, method, url string, jsonData interface{}) (*http.Request, error) {
var buf io.Reader
if jsonData != nil {
body, err := json.Marshal(jsonData)
if err != nil {
return nil, err
}
buf = bytes.NewBuffer(body)
}
req, err := http.NewRequestWithContext(ctx, method, url, buf)
if err != nil {
return nil, err
}
return req, nil
}