-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
89 lines (71 loc) · 1.52 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
package graphql
import (
"bytes"
"context"
"encoding/json"
"io/ioutil"
"net/http"
)
type Doer interface {
Do(req *http.Request) (*http.Response, error)
}
type Client struct {
endpoint string
header http.Header
httpClient Doer
}
func New(endpoint string, opts ...Option) *Client {
header := http.Header{}
header.Set("Content-Type", "application/graphql")
c := &Client{
endpoint: endpoint,
header: header,
}
for _, opt := range opts {
opt.Apply(c)
}
if c.httpClient == nil {
c.httpClient = http.DefaultClient
}
return c
}
func (c *Client) Post(ctx context.Context, request *Request, response *Response) (err error) {
reqBody, err := json.Marshal(request)
if err != nil {
return err
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.endpoint, bytes.NewReader(reqBody))
if err != nil {
return err
}
for k, v := range c.header {
req.Header[k] = v
}
for k, v := range request.header {
req.Header[k] = v
}
resp, err := c.httpClient.Do(req)
if err != nil {
return err
}
defer func() {
if e := resp.Body.Close(); e != nil {
err = e // replace with body close error
}
}()
response.StatusCode = resp.StatusCode
if http.StatusBadRequest <= resp.StatusCode {
response.Errors = Errors{ // will be overridden if response includes errors
Error{Message: http.StatusText(resp.StatusCode)},
}
}
respBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
err = json.Unmarshal(respBody, &response)
if err != nil {
return err
}
return nil
}