-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathcall.go
65 lines (52 loc) · 1.43 KB
/
call.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
package jaal
import (
"bytes"
"encoding/json"
"io/ioutil"
"net/http"
"time"
"go.appointy.com/jaal/jerrors"
)
// HttpCall sends an HTTP Request to the specified url and returns response in map of map
func HttpCall(url, query string, variables map[string]interface{}, headers map[string]string) (map[string]interface{}, []*jerrors.Error) {
var (
requestBody = httpPostBody{
Query: query,
Variables: variables,
}
responseBody httpResponse
)
client := http.Client{
Timeout: time.Duration(500 * time.Second),
}
requestData, err := json.Marshal(requestBody)
if err != nil {
return nil, []*jerrors.Error{jerrors.ConvertError(err)}
}
request, err := http.NewRequest("POST", url, bytes.NewBuffer(requestData))
if err != nil {
return nil, []*jerrors.Error{jerrors.ConvertError(err)}
}
for key, value := range headers {
request.Header.Set(key, value)
}
response, err := client.Do(request)
if err != nil {
return nil, []*jerrors.Error{jerrors.ConvertError(err)}
}
responseData, err := ioutil.ReadAll(response.Body)
if err != nil {
return nil, []*jerrors.Error{jerrors.ConvertError(err)}
}
if err := json.Unmarshal(responseData, &responseBody); err != nil {
return nil, []*jerrors.Error{jerrors.ConvertError(err)}
}
if len(responseBody.Errors) > 0 {
return nil, responseBody.Errors
}
data, ok := (responseBody.Data).(map[string]interface{})
if !ok {
return nil, nil
}
return data, responseBody.Errors
}