-
Notifications
You must be signed in to change notification settings - Fork 1
/
connection.go
70 lines (56 loc) · 1.37 KB
/
connection.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
package gremji
import (
"net/url"
"github.com/gorilla/websocket"
"net/http"
"errors"
"log"
)
type Client struct {
Remote *url.URL
Ws *websocket.Conn
}
func NewClient(urlStr string) (*Client, error) {
r, err := url.Parse(urlStr)
if err != nil {
return nil, err
}
dialer := websocket.Dialer{}
ws, _, err := dialer.Dial(urlStr, http.Header{})
if err != nil {
log.Println(err)
return nil, err
}
return &Client{r,ws}, nil
}
func (c *Client) ExecQuery(query QueryArgs) (*Response, error) {
req := Query(query)
return c.Exec(req)
}
func (c *Client) Exec(req *Request) (*Response, error) {
requestMessage, err := GraphSONSerializer(req)
if err = c.Ws.WriteMessage(websocket.BinaryMessage, requestMessage); err != nil {
return nil, err
}
return c.ReadResponse()
}
func (c *Client) ReadResponse() (*Response, error) {
res := &Response{}
var err error
if err = c.Ws.ReadJSON(res); err != nil {
return nil, err
}
switch res.Status.Code {
case StatusNoContent:
return nil, nil
case StatusSuccess:
return res, nil
default:
if msg, exists := ErrorMsg[res.Status.Code]; exists {
err := errors.New(msg)
return nil, err
}
err := errors.New("An unknown error ocurred")
return nil, err
}
}