-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
81 lines (68 loc) · 1.67 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
package eywa
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
)
type Client struct {
endpoint string
httpClient *http.Client
headers map[string]string
}
type ClientOpts struct {
HTTPClient *http.Client
Headers map[string]string
}
// NewClient accepts a graphql endpoint and returns back a Client.
// It uses the http.DefaultClient as the underlying http client by default.
func NewClient(gqlEndpoint string, opt *ClientOpts) *Client {
c := &Client{
endpoint: gqlEndpoint,
httpClient: http.DefaultClient,
}
if opt != nil {
if opt.HTTPClient != nil {
c.httpClient = opt.HTTPClient
}
if len(opt.Headers) > 0 {
c.headers = opt.Headers
}
}
return c
}
func (c *Client) Do(ctx context.Context, q Queryable) (*bytes.Buffer, error) {
reqObj := graphqlRequest{
Query: q.Query(),
Variables: q.Variables(),
}
var reqBytes bytes.Buffer
err := json.NewEncoder(&reqBytes).Encode(&reqObj)
if err != nil {
return nil, err
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.endpoint, &reqBytes)
if err != nil {
return nil, err
}
req.Header.Add("Content-Type", "application/json")
for key, value := range c.headers {
req.Header.Add(key, value)
}
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
switch {
case resp.StatusCode > 299 && resp.StatusCode < 399:
return nil, fmt.Errorf("redirected request with http status code: %d", resp.StatusCode)
case resp.StatusCode > 399:
return nil, fmt.Errorf("error response with http status code: %d", resp.StatusCode)
}
var respBytes bytes.Buffer
_, err = io.Copy(&respBytes, resp.Body)
return &respBytes, err
}