-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathgraphql.go
41 lines (35 loc) · 908 Bytes
/
graphql.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
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
)
type graphqlQuery struct {
Query string `json:"query"`
Variables map[string]interface{} `json:"variables"`
}
func doGraphQLQuery(ctx context.Context, url string, hc *http.Client, qreq *graphqlQuery) ([]byte, *http.Response, error) {
bodyJSON, err := json.Marshal(qreq)
if err != nil {
return nil, nil, err
}
body := bytes.NewReader(bodyJSON)
httpReq, err := http.NewRequestWithContext(ctx, "POST", url, body)
if err != nil {
return nil, nil, err
}
httpReq.Header.Set("Content-Type", "application/json")
httpResp, err := hc.Do(httpReq)
if err != nil {
return nil, nil, err
}
defer httpResp.Body.Close()
b, err := io.ReadAll(httpResp.Body)
if httpResp.StatusCode != 200 {
return nil, httpResp, fmt.Errorf("%s: got body %q", httpResp.Status, b)
}
return b, httpResp, err
}