-
Notifications
You must be signed in to change notification settings - Fork 1
/
client.go
105 lines (86 loc) · 2.16 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
98
99
100
101
102
103
104
105
package ghc
import (
"bytes"
"encoding/json"
"errors"
"net/http"
"net/url"
"reflect"
"github.com/valyala/fasthttp"
)
// Options ...
type Options struct {
Header http.Header
}
// Client ....
type Client struct {
u *url.URL
opts *Options
httpClient *fasthttp.Client
}
// New ...
func New(apiURL string, opts *Options) (*Client, error) {
var (
err error
url *url.URL
cl *fasthttp.Client
)
if opts != nil {
if cl, err = initHTTPClient(opts); err != nil {
return nil, errors.New("can't configure client:" + err.Error())
}
}
u, err := url.Parse(apiURL)
if err != nil {
return nil, err
}
return &Client{u: u, opts: opts, httpClient: cl}, nil
}
// Execute ...
func (c *Client) Execute(req *Request) (*Response, error) {
data, err := json.Marshal(req)
if err != nil {
return nil, errors.New("execute: marshal error: " + err.Error())
}
switch req.Type() {
case reflect.TypeOf(Query("")), reflect.TypeOf(Mutation("")):
return c.httpExecute(c.u, data)
case reflect.TypeOf(Subscription("")):
return c.wsExecute(c.u, data)
default:
return nil, errors.New("execute: unsupported request type: " + req.Type().String())
}
}
func (c *Client) httpExecute(u *url.URL, data []byte) (*Response, error) {
req := fasthttp.AcquireRequest()
req.Header.SetMethod("POST")
req.SetRequestURI(u.String())
req.SetBody(data)
if c.opts != nil && c.opts.Header != nil {
for k, v := range c.opts.Header {
for _, h := range v {
req.Header.Add(k, h)
}
}
}
res := fasthttp.AcquireResponse()
err := c.httpClient.Do(req, res)
if err != nil {
return nil, errors.New("execute: request: " + err.Error())
}
resp := &Response{}
decoder := json.NewDecoder(bytes.NewReader(res.Body()))
if err = decoder.Decode(resp); err != nil {
return nil, errors.New("execute: decode response: " + err.Error())
}
if resp.Errors != nil {
return resp, errors.New("execute: server returned error: see response.Errors for details")
}
return resp, nil
}
func (c *Client) wsExecute(u *url.URL, data []byte) (*Response, error) {
panic("isn't supported yet")
}
func initHTTPClient(opts *Options) (*fasthttp.Client, error) {
return &fasthttp.Client{}, nil
}