-
Notifications
You must be signed in to change notification settings - Fork 13
/
call.go
67 lines (56 loc) · 1.24 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
66
67
package helper
import (
"bytes"
"context"
"encoding/json"
"errors"
"io"
"io/ioutil"
"net/http"
"strings"
"time"
)
// Call helper for api calls
// TODO : make service and use debug service to
func Call(ctx context.Context,
method,
url string,
headers map[string]string,
timeout time.Duration,
payload interface{},
cookies []*http.Cookie) ([]byte, http.Header, int, error) {
d, err := json.Marshal(payload)
if err != nil {
panic(err)
}
var b io.Reader
b = bytes.NewReader(d)
method = strings.ToUpper(method)
if StringInArray(method, "GET", "DELETE") {
b = nil
}
r, err := http.NewRequest(method, url, b)
if err != nil {
return nil, nil, 0, errors.New("error while creating request")
}
for i := range headers {
r.Header.Set(i, headers[i])
}
for i := range cookies {
r.AddCookie(cookies[i])
}
nCtx, cnl := context.WithTimeout(ctx, timeout)
defer cnl()
resp, err := http.DefaultClient.Do(r.WithContext(nCtx))
if err != nil {
return nil, nil, 0, errors.New("error in return response")
}
data, err := ioutil.ReadAll(resp.Body)
defer func() {
_ = resp.Body.Close()
}()
if err != nil {
return nil, nil, resp.StatusCode, errors.New("error in reading response")
}
return data, resp.Header, resp.StatusCode, nil
}