-
Notifications
You must be signed in to change notification settings - Fork 13
/
call.go
131 lines (105 loc) · 2.23 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
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
package helper
import (
"bytes"
"context"
"encoding/json"
"encoding/xml"
"errors"
"io"
"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) {
var d []byte
var e error
switch v := payload.(type) {
case string:
d = []byte(v)
default:
d, e = json.Marshal(v)
if e != nil {
panic(e)
}
}
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, err
}
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 := io.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
}
func CallXML(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 := xml.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, err
}
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, err
}
data, err := io.ReadAll(resp.Body)
defer func() {
_ = resp.Body.Close()
}()
if err != nil {
return nil, nil, resp.StatusCode, err
}
return data, resp.Header, resp.StatusCode, nil
}