-
Notifications
You must be signed in to change notification settings - Fork 74
Expand file tree
/
Copy pathreq.go
More file actions
53 lines (43 loc) · 1.24 KB
/
req.go
File metadata and controls
53 lines (43 loc) · 1.24 KB
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
package utils
import (
"bytes"
"crypto/tls"
"encoding/json"
"fmt"
"io"
"net/http"
)
func DoReq[response any](url string, data []byte, method string, headers map[string]string, skipTlsVerification bool) (response, int, error) {
var result response
req, err := http.NewRequest(method, url, bytes.NewBuffer(data))
if err != nil {
return result, http.StatusInternalServerError, err
}
for k, v := range headers {
req.Header.Add(k, v)
}
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: skipTlsVerification},
}
client := &http.Client{Transport: tr}
defer tr.CloseIdleConnections()
resp, err := client.Do(req)
if err != nil {
return result, http.StatusInternalServerError, err
}
defer func() {
_ = resp.Body.Close()
}()
body, err := io.ReadAll(resp.Body)
if err != nil {
return result, http.StatusInternalServerError, err
}
if resp.StatusCode != http.StatusAccepted && resp.StatusCode != http.StatusOK {
return result, resp.StatusCode, fmt.Errorf("while sending request to %s received status code: %d and response body: %s", url, resp.StatusCode, body)
}
err = json.Unmarshal(body, &result)
if err != nil {
return result, http.StatusInternalServerError, err
}
return result, resp.StatusCode, nil
}