forked from thani-sh/go-graphiql
-
Notifications
You must be signed in to change notification settings - Fork 1
/
client.go
92 lines (77 loc) · 1.6 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
package graphiql
import (
"bytes"
"encoding/json"
"net/http"
"net/url"
)
// GraphQLError ...
type GraphQLError struct {
Message string `json:"message"`
}
// GraphQLError implements error interface
func (e *GraphQLError) Error() string {
return e.Message
}
// Request ...
type Request struct {
Query string `json:"query"`
}
// Response ...
type Response struct {
Data *json.RawMessage `json:"data"`
Errors []GraphQLError `json:"errors,omitempty"`
}
// Client ...
type Client struct {
Endpoint string
Header http.Header
Client http.Client
}
// NewClient ...
func NewClient(uri string) (c *Client, err error) {
c = &Client{
Endpoint: uri,
Header: http.Header{},
Client: http.Client{},
}
c.Header.Set("Content-Type", "application/json")
u, err := url.Parse(uri)
if err != nil {
return nil, err
}
if u.User == nil {
return c, nil
}
user := u.User.Username()
pass, hasPass := u.User.Password()
if user != "" && hasPass && pass != "" {
req := http.Request{Header: c.Header}
req.SetBasicAuth(user, pass)
}
u.User = nil
c.Endpoint = u.String()
return c, nil
}
// Send ...
func (c *Client) Send(req *Request) (res *Response, err error) {
body, err := json.Marshal(req)
if err != nil {
return nil, err
}
bodyBuf := bytes.NewBuffer(body)
httpReq, err := http.NewRequest(http.MethodPost, c.Endpoint, bodyBuf)
if err != nil {
return nil, err
}
httpReq.Header = c.Header
httpRes, err := c.Client.Do(httpReq)
if err != nil {
return nil, err
}
res = &Response{}
if err := json.NewDecoder(httpRes.Body).Decode(res); err != nil {
return nil, err
}
return res, nil
}