-
Notifications
You must be signed in to change notification settings - Fork 1
/
http.go
213 lines (178 loc) · 4.96 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
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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
package mt
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/http/httptest"
"net/url"
"os"
"strings"
"time"
mtjson "github.com/jefflinse/melatonin/json"
)
var (
defaultRequestTimeout = 10 * time.Second
)
func init() {
envTimeoutStr := os.Getenv("MELATONIN_DEFAULT_TEST_TIMEOUT")
if envTimeoutStr != "" {
if timeout, err := time.ParseDuration(envTimeoutStr); err == nil {
defaultRequestTimeout = timeout
} else {
fmt.Printf("invalid MELATONIN_DEFAULT_TEST_TIMEOUT value %q in environment, using default of %s\n",
envTimeoutStr, defaultRequestTimeout)
}
}
}
// DELETE is a shortcut for DefaultContext().NewTestCase(http.MethodDelete, path).
func DELETE(url string, description ...string) *HTTPTestCase {
return DefaultContext().DELETE(url, description...)
}
// HEAD is a shortcut for NewTestCase(http.MethodHead, path, description...).
func HEAD(url string, description ...string) *HTTPTestCase {
return DefaultContext().HEAD(url, description...)
}
// GET is a shortcut for NewTestCase(http.MethodGet, path, description...).
func GET(url string, description ...string) *HTTPTestCase {
return DefaultContext().GET(url, description...)
}
// OPTIONS is a shortcut for NewTestCase(http.MethodOptions, path, description...).
func OPTIONS(url string, description ...string) *HTTPTestCase {
return DefaultContext().OPTIONS(url, description...)
}
// PATCH is a shortcut for NewTestCase(http.MethodPatch, path, description...).
func PATCH(url string, description ...string) *HTTPTestCase {
return DefaultContext().PATCH(url, description...)
}
// POST is a shortcut for NewTestCase(http.MethodPost, path, description...).
func POST(url string, description ...string) *HTTPTestCase {
return DefaultContext().POST(url, description...)
}
// PUT is a shortcut for NewTestCase(http.MethodPut, path, description...).
func PUT(url string, description ...string) *HTTPTestCase {
return DefaultContext().PUT(url, description...)
}
// DO creates a test case from a custom HTTP request.
func DO(request *http.Request, description ...string) *HTTPTestCase {
tc := DefaultContext().newHTTPTestCase(request.Method, request.URL.Path, description...)
tc.request = request
return tc
}
func createRequest(method, path string) (*http.Request, context.CancelFunc, error) {
ctx, cancel := context.WithTimeout(context.Background(), defaultRequestTimeout)
req, err := http.NewRequestWithContext(ctx, method, path, nil)
if err != nil {
return nil, cancel, err
}
return req, cancel, nil
}
func doRequest(c *http.Client, req *http.Request) (int, http.Header, []byte, error) {
resp, err := c.Do(req)
if err != nil {
return -1, nil, nil, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return -1, nil, nil, err
}
return resp.StatusCode, resp.Header, body, nil
}
func handleRequest(h http.Handler, req *http.Request) (int, http.Header, []byte, error) {
w := httptest.NewRecorder()
h.ServeHTTP(w, req)
resp := w.Result()
b, err := ioutil.ReadAll(resp.Body)
return resp.StatusCode, resp.Header, b, err
}
func toBytes(body any) ([]byte, error) {
var b []byte
if body != nil {
var err error
switch v := body.(type) {
case []byte:
b = v
case string:
b = []byte(v)
case func() []byte:
b = v()
case func() ([]byte, error):
b, err = v()
default:
b, err = json.Marshal(body)
}
if err != nil {
return nil, fmt.Errorf("request body: %w", err)
}
}
return b, nil
}
func toInterface(body []byte) any {
if len(body) > 0 {
var bodyMap map[string]any
if err := json.Unmarshal(body, &bodyMap); err == nil {
return bodyMap
}
var bodyArray []any
if err := json.Unmarshal(body, &bodyArray); err == nil {
return bodyArray
}
return string(body)
}
return nil
}
type parameters map[string]any
// Apply maps the values to a target path.
func (p parameters) applyTo(path string) (string, error) {
resolved, err := mtjson.ResolveDeferred(map[string]any(p))
if err != nil {
return "", err
}
result := path
for k, v := range resolved.(map[string]any) {
str, err := paramString(v)
if err != nil {
return "", err
}
result = strings.ReplaceAll(result, ":"+k, str)
if err != nil {
return "", err
}
}
return result, nil
}
func paramString(v any) (string, error) {
str := ""
switch value := v.(type) {
case bool:
str = fmt.Sprintf("%t", value)
case float32, float64:
str = fmt.Sprintf("%g", value)
case int, int32, int64, uint, uint32, uint64:
str = fmt.Sprintf("%d", value)
case string:
str = value
case []string:
str = strings.Join(value, ",")
default:
return "", fmt.Errorf("unsupported parameter type: %T", value)
}
return str, nil
}
func (p parameters) asRawQuery() (string, error) {
resolved, err := mtjson.ResolveDeferred(map[string]any(p))
if err != nil {
return "", err
}
params := url.Values{}
for k, v := range resolved.(map[string]any) {
str, err := paramString(v)
if err != nil {
return "", err
}
params.Add(k, str)
}
return params.Encode(), nil
}