forked from go-gremlin/gremlin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathresponse.go
103 lines (92 loc) · 2.37 KB
/
response.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
package gremlin
import (
"encoding/json"
"errors"
"time"
"github.com/gorilla/websocket"
)
type Response struct {
RequestId string `json:"requestId"`
Status *ResponseStatus `json:"status"`
Result *ResponseResult `json:"result"`
}
type ResponseStatus struct {
Code int `json:"code"`
Attributes map[string]interface{} `json:"attributes"`
Message string `json:"message"`
}
type ResponseResult struct {
Data json.RawMessage `json:"data"`
Meta map[string]interface{} `json:"meta"`
}
func ReadResponse(ws *websocket.Conn) (data []byte, err error) {
// Data buffer
var message []byte
var dataItems []json.RawMessage
inBatchMode := false
// Receive data
for {
if _, message, err = ws.ReadMessage(); err != nil {
return
}
var res *Response
if err = json.Unmarshal(message, &res); err != nil {
return
}
var items []json.RawMessage
switch res.Status.Code {
case StatusNoContent:
return
case StatusPartialContent:
inBatchMode = true
if err = json.Unmarshal(res.Result.Data, &items); err != nil {
return
}
dataItems = append(dataItems, items...)
case StatusSuccess:
if inBatchMode {
if err = json.Unmarshal(res.Result.Data, &items); err != nil {
return
}
dataItems = append(dataItems, items...)
data, err = json.Marshal(dataItems)
} else {
data = res.Result.Data
}
return
default:
if msg, exists := ErrorMsg[res.Status.Code]; exists {
err = errors.New(msg)
} else {
err = errors.New("An unknown error occured")
}
data = []byte(res.Status.Message)
return
}
}
return
}
func (req *Request) Exec() (data []byte, err error) {
// Prepare the Data
message, err := json.Marshal(req)
if err != nil {
return
}
// Prepare the request message
var requestMessage []byte
mimeType := []byte("application/json")
mimeTypeLen := byte(len(mimeType))
requestMessage = append(requestMessage, mimeTypeLen)
requestMessage = append(requestMessage, mimeType...)
requestMessage = append(requestMessage, message...)
if err = req.conn.ws.SetWriteDeadline(time.Now().Add(10 * time.Second)); err != nil {
return
}
if err = req.conn.ws.SetReadDeadline(time.Now().Add(10 * time.Second)); err != nil {
return
}
if err = req.conn.ws.WriteMessage(websocket.BinaryMessage, requestMessage); err != nil {
return
}
return ReadResponse(req.conn.ws)
}