-
Notifications
You must be signed in to change notification settings - Fork 13
/
http.go
101 lines (80 loc) · 2.03 KB
/
http.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
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"github.com/pkg/errors"
"github.com/coretrix/hitrix/pkg/test"
)
func SendHTTPRequest(env *test.Environment, method string, pathAndQuery string, authenticate bool, response interface{}) error {
ts := httptest.NewServer(env.GinEngine)
defer ts.Close()
r, err := http.NewRequestWithContext(env.Cxt, method, ts.URL+"/v1"+pathAndQuery, nil)
if err != nil {
return err
}
if authenticate {
r.Header.Set("Authorization", "Bearer accessToken")
}
return sendHTTPRequest(r, response)
}
func SendHTTPRequestWithBody(
env *test.Environment,
method string,
pathAndQuery string,
input interface{},
authenticate bool,
response interface{},
) error {
return SendHTTPRequestWithBodyAndHeaders(env, method, pathAndQuery, input, authenticate, response, map[string]string{})
}
func SendHTTPRequestWithBodyAndHeaders(
env *test.Environment,
method string,
pathAndQuery string,
input interface{},
authenticate bool,
response interface{},
headers map[string]string,
) error {
body, err := json.Marshal(input)
if err != nil {
return errors.Wrap(err, "could not marshal post params")
}
ts := httptest.NewServer(env.GinEngine)
defer ts.Close()
r, err := http.NewRequestWithContext(env.Cxt, method, ts.URL+"/v1"+pathAndQuery, bytes.NewBuffer(body))
if err != nil {
return err
}
for key, value := range headers {
r.Header.Set(key, value)
}
if authenticate {
r.Header.Set("Authorization", "Bearer accessToken")
}
return sendHTTPRequest(r, response)
}
func sendHTTPRequest(request *http.Request, response interface{}) error {
w, err := http.DefaultClient.Do(request)
if err != nil {
return err
}
defer w.Body.Close()
body, err := io.ReadAll(w.Body)
if err != nil {
return err
}
if w.StatusCode != http.StatusOK {
return fmt.Errorf("got http status %d : %s", w.StatusCode, string(body))
}
res := response
err = json.Unmarshal(body, &res)
if err != nil {
return errors.Wrap(err, "could not unmarshal response")
}
return nil
}