-
Notifications
You must be signed in to change notification settings - Fork 1
/
http.go
294 lines (267 loc) · 7.97 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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
// Package http the http JS implementation
package http
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"mime/multipart"
"net/http"
urlpkg "net/url"
"strings"
"github.com/dop251/goja"
"github.com/shiroyk/cloudcat"
"github.com/shiroyk/cloudcat/js"
"github.com/shiroyk/cloudcat/plugin/jsmodule"
"github.com/spf13/cast"
"golang.org/x/net/http/httpguts"
)
// Module js module
type Module struct{}
// Exports returns module instance
func (*Module) Exports() any {
return &Http{cloudcat.MustResolve[cloudcat.Fetch]()}
}
func init() {
jsmodule.Register("http", new(Module))
jsmodule.Register("fetch", new(FetchModule))
jsmodule.Register("FormData", new(FormDataConstructor))
jsmodule.Register("URLSearchParams", new(URLSearchParamsConstructor))
jsmodule.Register("AbortController", new(AbortControllerConstructor))
jsmodule.Register("AbortSignal", new(AbortSignalModule))
}
// FetchModule the global fetch() method starts the process of
// fetching a resource from the network, returning a promise
// which is fulfilled once the response is available.
// https://developer.mozilla.org/en-US/docs/Web/API/fetch
type FetchModule struct{}
func (*FetchModule) Exports() any {
f := cloudcat.MustResolve[cloudcat.Fetch]()
return func(call goja.FunctionCall, vm *goja.Runtime) goja.Value {
req, signal := buildRequest(http.MethodGet, call, vm)
callback := js.NewEnqueueCallback(vm)
promise, resolve, reject := vm.NewPromise()
go func() {
if signal != nil {
defer signal.abort() // release resources
}
res, err := f.Do(req)
callback(func() error {
if err != nil {
reject(err)
} else {
resolve(NewAsyncResponse(vm, res))
}
return nil
})
}()
return vm.ToValue(promise)
}
}
func (*FetchModule) Global() {}
// Http module for fetching resources (including across the network).
type Http struct { //nolint
fetch cloudcat.Fetch
}
// Get Make a HTTP GET request.
func (h *Http) Get(call goja.FunctionCall, vm *goja.Runtime) goja.Value {
return doRequest(h.fetch, http.MethodGet, call, vm)
}
// Post Make a HTTP POST.
// Send POST with multipart:
// http.post(url, { body: new FormData({'bytes': new Uint8Array([0]).buffer}) })
// Send POST with x-www-form-urlencoded:
// http.post(url, { body: new URLSearchParams({'key': 'foo', 'value': 'bar'}) })
// Send POST with json:
// http.post(url, { body: {'key': 'foo'} })
func (h *Http) Post(call goja.FunctionCall, vm *goja.Runtime) goja.Value {
return doRequest(h.fetch, http.MethodPost, call, vm)
}
// Put Make a HTTP PUT request.
func (h *Http) Put(call goja.FunctionCall, vm *goja.Runtime) goja.Value {
return doRequest(h.fetch, http.MethodPut, call, vm)
}
// Delete Make a HTTP DELETE request.
func (h *Http) Delete(call goja.FunctionCall, vm *goja.Runtime) goja.Value {
return doRequest(h.fetch, http.MethodDelete, call, vm)
}
// Patch Make a HTTP PATCH request.
func (h *Http) Patch(call goja.FunctionCall, vm *goja.Runtime) goja.Value {
return doRequest(h.fetch, http.MethodPatch, call, vm)
}
// Request Make a HTTP request.
func (h *Http) Request(call goja.FunctionCall, vm *goja.Runtime) goja.Value {
return doRequest(h.fetch, http.MethodGet, call, vm)
}
// Head Make a HTTP HEAD request.
func (h *Http) Head(call goja.FunctionCall, vm *goja.Runtime) goja.Value {
return doRequest(h.fetch, http.MethodHead, call, vm)
}
func buildRequest(
method string,
call goja.FunctionCall,
vm *goja.Runtime,
) (req *http.Request, signal *AbortSignal) {
url := call.Argument(0).String()
opt := call.Argument(1)
var body io.Reader
var headers = make(map[string]string)
var proxy *urlpkg.URL
var err error
if opt != nil && !goja.IsUndefined(opt) {
options, assert := opt.Export().(map[string]any)
if !assert {
js.Throw(vm, errors.New("request options is invalid"))
}
if v, ok := options["method"]; ok {
method, err = cast.ToStringE(v)
if err != nil {
js.Throw(vm, errors.New("request options method is invalid string"))
}
method = strings.ToUpper(method)
if !validMethod(method) {
js.Throw(vm, fmt.Errorf("request options method %v is invalid HTTP method", method))
}
}
if v, ok := options["headers"]; ok {
headers, err = cast.ToStringMapStringE(v)
if err != nil {
js.Throw(vm, errors.New("request options headers is invalid"))
}
}
if v, ok := options["body"]; ok {
body, err = handleBody(v, headers)
if err != nil {
js.Throw(vm, err)
}
}
if v, ok := options["cache"]; ok {
str, err := cast.ToStringE(v)
if err != nil {
js.Throw(vm, errors.New("request options cache is invalid string"))
}
headers["Cache-Control"] = str
headers["Pragma"] = str
}
if v, ok := options["proxy"]; ok {
str, err := cast.ToStringE(v)
if err != nil {
js.Throw(vm, errors.New("request options proxy is invalid string"))
}
proxy, err = urlpkg.Parse(str)
if err != nil {
js.Throw(vm, errors.Join(errors.New("request options proxy is invalid URL"), err))
}
}
if v, ok := options["signal"]; ok {
signal, ok = v.(*AbortSignal)
if !ok {
js.Throw(vm, errors.New("request options signal is invalid AbortSignal"))
}
}
}
var parent context.Context
if signal != nil {
parent = signal.ctx
} else {
parent = js.VMContext(vm)
}
ctx := cloudcat.WithProxyURL(parent, proxy)
req, err = http.NewRequestWithContext(ctx, method, url, body)
if err != nil {
js.Throw(vm, err)
}
for k, v := range headers {
req.Header.Set(k, v)
}
return
}
func doRequest(
fetch cloudcat.Fetch,
method string,
call goja.FunctionCall,
vm *goja.Runtime,
) goja.Value {
req, signal := buildRequest(method, call, vm)
if signal != nil {
defer signal.abort() // release resources
}
res, err := fetch.Do(req)
if err != nil {
js.Throw(vm, err)
}
return NewResponse(vm, res)
}
func validMethod(method string) bool {
/*
Method = "OPTIONS" ; Section 9.2
| "GET" ; Section 9.3
| "HEAD" ; Section 9.4
| "POST" ; Section 9.5
| "PUT" ; Section 9.6
| "DELETE" ; Section 9.7
| "TRACE" ; Section 9.8
| "CONNECT" ; Section 9.9
| extension-method
extension-method = token
token = 1*<any CHAR except CTLs or separators>
*/
return len(method) > 0 && strings.IndexFunc(method, func(r rune) bool {
return !httpguts.IsTokenRune(r)
}) == -1
}
// handleBody process the send request body and set the content-type
func handleBody(body any, headers map[string]string) (io.Reader, error) {
switch data := body.(type) {
case FormData:
buf := new(bytes.Buffer)
mpw := multipart.NewWriter(buf)
for k, v := range data.data {
for _, ve := range v {
if f, ok := ve.(FileData); ok {
// Creates a new form-data header with the provided field name and file name.
fw, err := mpw.CreateFormFile(k, f.Filename)
if err != nil {
return nil, err
}
// Write bytes to the part
if _, err := fw.Write(f.Data); err != nil {
return nil, err
}
} else {
// Write string value
if err := mpw.WriteField(k, fmt.Sprintf("%v", v)); err != nil {
return nil, err
}
}
}
}
headers["Content-Type"] = mpw.FormDataContentType()
if err := mpw.Close(); err != nil {
return nil, err
}
return buf, nil
case URLSearchParams:
headers["Content-Type"] = "application/x-www-form-url"
return strings.NewReader(data.encode()), nil
case string:
return strings.NewReader(data), nil
case goja.ArrayBuffer:
return bytes.NewReader(data.Bytes()), nil
case []byte:
return bytes.NewReader(data), nil
case map[string]any:
headers["Content-Type"] = "application/json"
marshal, err := json.Marshal(data)
if err != nil {
return nil, err
}
return bytes.NewReader(marshal), nil
case nil:
return http.NoBody, nil
default:
return nil, fmt.Errorf("unsupported request body type %T", body)
}
}