-
Notifications
You must be signed in to change notification settings - Fork 1
/
request_wrapper.go
98 lines (86 loc) · 2.39 KB
/
request_wrapper.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
package fetch
import (
"fmt"
"io"
"net/http"
"reflect"
"go.miragespace.co/heresy/extensions/common"
"go.miragespace.co/heresy/extensions/stream"
"github.com/dop251/goja"
pool "github.com/libp2p/go-buffer-pool"
)
type NativeFetchWrapper struct {
cfg FetchConfig
ioContext *common.IOContext
}
func (f *NativeFetchWrapper) doFetch(fc goja.FunctionCall, vm *goja.Runtime) (ret goja.Value) {
promise, resolve, reject := vm.NewPromise()
ret = vm.ToValue(promise)
var (
reqURL = fc.Argument(0)
reqMethod = fc.Argument(1)
reqHeaders = fc.Argument(2)
reqBody = fc.Argument(3)
result = f.cfg.Stream.GetResponseProxy(f.ioContext)
bodyType = reqBody.ExportType()
url string = reqURL.String()
method string = reqMethod.String()
headers map[string]any = reqHeaders.Export().(map[string]any)
useBody io.Reader = nil
)
if goja.IsUndefined(reqBody) || goja.IsNull(reqBody) {
// no body
useBody = http.NoBody
} else if bodyType.Kind() == reflect.String {
strBuf := pool.NewBufferString(reqBody.String())
f.ioContext.RegisterCleanup(strBuf.Reset)
useBody = strBuf
} else {
// possibly wrapped ReadableStream
reader, ok := stream.AssertReader(reqBody, vm)
if !ok {
f.cfg.Eventloop.RunOnLoop(func(vm *goja.Runtime) {
reject(vm.NewGoError(ErrUnsupportedReadableStream))
})
return
}
useBody = reader
}
go func() {
err := f.ioContext.AcquireFetchToken()
if err != nil {
f.cfg.Eventloop.RunOnLoop(func(vm *goja.Runtime) {
reject(vm.NewGoError(err))
})
return
}
defer f.ioContext.ReleaseFetchToken()
req, err := http.NewRequestWithContext(f.ioContext.Context(), method, url, useBody)
if err != nil {
f.cfg.Eventloop.RunOnLoop(func(vm *goja.Runtime) {
reject(vm.NewGoError(err))
})
return
}
for k, v := range headers {
if s, ok := v.(string); ok {
req.Header.Set(k, s)
} else {
req.Header.Set(k, fmt.Sprintf("%s", v))
}
}
req.Header.Set("user-agent", UserAgent)
resp, err := f.cfg.Client.Do(req)
if err != nil {
f.cfg.Eventloop.RunOnLoop(func(vm *goja.Runtime) {
reject(vm.NewGoError(err))
})
} else {
f.cfg.Eventloop.RunOnLoop(func(vm *goja.Runtime) {
result.WithResponse(f.ioContext, vm, resp)
resolve(result.NativeObject())
})
}
}()
return
}