/
http_client.go
105 lines (86 loc) · 2.24 KB
/
http_client.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
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
package cmd
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/http/httputil"
"net/url"
"path"
"github.com/pkg/errors"
)
// Client use HTTP access
type Client struct {
EndpointURL *url.URL
HTTPClient *http.Client
}
func createClient(endpointURL string, httpClient *http.Client) (*Client, error) {
parsedURL, err := url.Parse(endpointURL)
if err != nil {
return nil, errors.Wrapf(err, "failed to parse url: %s", endpointURL)
}
client := &Client{
EndpointURL: parsedURL,
HTTPClient: httpClient,
}
return client, nil
}
func (client *Client) createRequest(ctx context.Context, method string, subPath string, apiKey string, body io.Reader) (*http.Request, error) {
endpointURL := *client.EndpointURL
endpointURL.Path = path.Join(client.EndpointURL.Path, subPath)
req, err := http.NewRequest(method, endpointURL.String(), body)
if err != nil {
return nil, err
}
req = req.WithContext(ctx)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("User-Agent", "ca-cli/v000")
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", apiKey))
return req, nil
}
func decodeBody(resp *http.Response, out interface{}) error {
defer resp.Body.Close()
decoder := json.NewDecoder(resp.Body)
return decoder.Decode(out)
}
func getBodyString(resp *http.Response) (string, error) {
defer resp.Body.Close()
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
// check http error
if resp.StatusCode >= http.StatusBadRequest {
// to-dp: JSON format may be more convenient?
return "", fmt.Errorf("\nResponse Code: %d\nResponse Body: %s\n", resp.StatusCode, string(b))
}
// body data is none
if len(b) <= 0 {
b = []byte(fmt.Sprintf("{\"response_code\":\"%d\"}", resp.StatusCode))
}
// indent 4 space
var prettyJSON bytes.Buffer
if err := json.Indent(&prettyJSON, b, "", " "); err != nil {
return "", err
}
return prettyJSON.String(), nil
}
func dumpHTTPRequest(req *http.Request) {
dump, err := httputil.DumpRequest(req, true)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(dump))
}
func dumpHTTPResponse(resp *http.Response) {
dump, err := httputil.DumpResponse(resp, true)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(dump))
}