-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathclient.go
97 lines (80 loc) · 1.97 KB
/
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
package microcms
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strings"
)
type httpClient interface {
Do(req *http.Request) (*http.Response, error)
}
type Client struct {
serviceDomain string
apiKey string
httpClient httpClient
}
func New(serviceDomain, apiKey string) *Client {
c := &Client{
serviceDomain: serviceDomain,
apiKey: apiKey,
httpClient: http.DefaultClient,
}
return c
}
func (c *Client) SetHTTPClient(client httpClient) {
c.httpClient = client
}
func makeRequest(c *Client, method, endpoint string, query url.Values, data interface{}) (*http.Request, error) {
url := fmt.Sprintf("https://%s.%s/api/%s/%s", c.serviceDomain, BaseDomain, APIVersion, endpoint)
if len(query) > 0 {
url = fmt.Sprintf("%s?%s", url, query.Encode())
}
buf := new(bytes.Buffer)
if data != nil {
if err := json.NewEncoder(buf).Encode(data); err != nil {
return nil, err
}
}
req, err := http.NewRequest(method, url, buf)
if err != nil {
return nil, err
}
req.Header.Set("X-MICROCMS-API-KEY", c.apiKey)
if data != nil {
req.Header.Set("Content-Type", "application/json; charset=utf-8")
}
return req, nil
}
func sendRequest(c *Client, req *http.Request, data interface{}) error {
res, err := c.httpClient.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
if res.StatusCode >= 400 {
errorMessage, err := ioutil.ReadAll(res.Body)
if err != nil {
return fmt.Errorf("microCMS connection error: %w", err)
}
return &HttpResponseError{
Response: res,
ErrorMessage: string(errorMessage),
}
}
if strings.Contains(res.Header.Get("Content-Type"), "application/json") {
if err := json.NewDecoder(res.Body).Decode(data); err != nil {
return err
}
}
return nil
}
type HttpResponseError struct {
Response *http.Response
ErrorMessage string
}
func (r *HttpResponseError) Error() string {
return fmt.Sprintf("response error: StatusCode=%d %s", r.Response.StatusCode, r.ErrorMessage)
}