-
Notifications
You must be signed in to change notification settings - Fork 9
/
request.go
145 lines (118 loc) · 2.48 KB
/
request.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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
package neo4j
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strings"
)
// ManuelRequest struct for create a custom Neo4J request
// This is particularly used for creating Batch opeartion requests
type ManuelRequest struct {
To string
Params map[string]string
Body map[string]string
}
// Get func
func (mr *ManuelRequest) Get() ([]string, error) {
urlWithParams := mr.encodeParams()
req, err := http.NewRequest("GET", urlWithParams, nil)
if err != nil {
return nil, err
}
resp, err := mr.getDeleteHelper(req)
if err != nil {
return nil, err
}
return resp, nil
}
// Delete func
func (mr *ManuelRequest) Delete() error {
urlWithParams := mr.encodeParams()
req, err := http.NewRequest("DELETE", urlWithParams, nil)
if err != nil {
return err
}
_, err = mr.getDeleteHelper(req)
if err != nil {
return err
}
return nil
}
func (mr *ManuelRequest) getDeleteHelper(req *http.Request) ([]string, error) {
client := &http.Client{}
res, err := client.Do(req)
if err != nil {
return nil, err
}
resp, err := mr.decodeResponse(res)
if err != nil {
return nil, err
}
return resp, nil
}
// Post func
func (mr *ManuelRequest) Post() error {
body, err := jsonEncode(mr.Body)
if err != nil {
return err
}
jsonBody := strings.NewReader(body)
req, err := http.NewRequest("POST", mr.To, jsonBody)
if err != nil {
return err
}
mr.encodeForm(req)
client := &http.Client{}
res, err := client.PostForm(mr.To, req.Form)
if err != nil {
return err
}
_, err = mr.decodeResponse(res)
if err != nil {
return err
}
defer res.Body.Close()
return nil
}
func (mr *ManuelRequest) decodeResponse(res *http.Response) ([]string, error) {
switch res.StatusCode {
case 200, 500:
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, err
}
var result = make([]string, 0)
err = json.Unmarshal(body, &result)
if err != nil {
return nil, err
}
return result, nil
case 204:
default:
return nil, fmt.Errorf(res.Status)
}
return nil, nil
}
func (mr *ManuelRequest) encodeParams() string {
var urlWithParams string
if mr.Params != nil {
params := url.Values{}
for key, value := range mr.Params {
params.Add(key, value)
}
urlWithParams = fmt.Sprintf("%s?%s", mr.To, params.Encode())
} else {
urlWithParams = mr.To
}
return urlWithParams
}
func (mr *ManuelRequest) encodeForm(req *http.Request) {
if mr.Body != nil {
req.Form = url.Values{}
for k, v := range mr.Body {
req.Form.Add(k, v)
}
}
}