-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathfetch.go
226 lines (192 loc) · 5.38 KB
/
fetch.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
package fetch
import (
"bytes"
"context"
"errors"
"io"
"syscall/js"
)
// Opts are the options you can pass to the fetch call.
type Opts struct {
// Method is the http verb (constants are copied from net/http to avoid import)
Method string
// Headers is a map of http headers to send.
Headers map[string]string
// Body is the body request
Body io.Reader
// Mode docs https://developer.mozilla.org/en-US/docs/Web/API/Request/mode
Mode string
// Credentials docs https://developer.mozilla.org/en-US/docs/Web/API/Request/credentials
Credentials string
// Cache docs https://developer.mozilla.org/en-US/docs/Web/API/Request/cache
Cache string
// Redirect docs https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch
Redirect string
// Referrer docs https://developer.mozilla.org/en-US/docs/Web/API/Request/referrer
Referrer string
// ReferrerPolicy docs https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch
ReferrerPolicy string
// Integrity docs https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity
Integrity string
// KeepAlive docs https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch
KeepAlive *bool
// Signal docs https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal
Signal context.Context
}
// Response is the response that retursn from the fetch promise.
type Response struct {
Headers Header
OK bool
Redirected bool
Status int
StatusText string
Type string
URL string
Body []byte
BodyUsed bool
}
// Fetch uses the JS Fetch API to make requests
// over WASM.
func Fetch(url string, opts *Opts) (*Response, error) {
optsMap, err := mapOpts(opts)
if err != nil {
return nil, err
}
type fetchResponse struct {
r *Response
b js.Value
e error
}
ch := make(chan *fetchResponse)
done := make(chan struct{}, 1)
if opts.Signal != nil {
controller := js.Global().Get("AbortController").New()
signal := controller.Get("signal")
optsMap["signal"] = signal
go func() {
select {
case <-opts.Signal.Done():
controller.Call("abort")
case <-done:
}
}()
}
success := js.FuncOf(func(this js.Value, args []js.Value) interface{} {
r := new(Response)
resp := args[0]
headersIt := resp.Get("headers").Call("entries")
headers := Header{}
for {
n := headersIt.Call("next")
if n.Get("done").Bool() {
break
}
pair := n.Get("value")
key, value := pair.Index(0).String(), pair.Index(1).String()
headers.Add(key, value)
}
r.Headers = headers
r.OK = resp.Get("ok").Bool()
r.Redirected = resp.Get("redirected").Bool()
r.Status = resp.Get("status").Int()
r.StatusText = resp.Get("statusText").String()
r.Type = resp.Get("type").String()
r.URL = resp.Get("url").String()
r.BodyUsed = resp.Get("bodyUsed").Bool()
ch <- &fetchResponse{r: r, b: resp}
return nil
})
defer success.Release()
failure := js.FuncOf(func(this js.Value, args []js.Value) interface{} {
msg := args[0].Get("message").String()
done <- struct{}{}
ch <- &fetchResponse{e: errors.New(msg)}
return nil
})
defer failure.Release()
go js.Global().Call("fetch", url, optsMap).Call("then", success).Call("catch", failure)
r := <-ch
if r.e != nil {
return nil, r.e
}
successBody := js.FuncOf(func(this js.Value, args []js.Value) interface{} {
// Wrap the input ArrayBuffer with a Uint8Array
uint8arrayWrapper := js.Global().Get("Uint8Array").New(args[0])
r.r.Body = make([]byte, uint8arrayWrapper.Get("byteLength").Int())
js.CopyBytesToGo(r.r.Body, uint8arrayWrapper)
ch <- r
return nil
})
defer successBody.Release()
failureBody := js.FuncOf(func(this js.Value, args []js.Value) interface{} {
// Assumes it's a TypeError. See
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError
// for more information on this type.
// See https://fetch.spec.whatwg.org/#concept-body-consume-body for error causes.
msg := args[0].Get("message").String()
ch <- &fetchResponse{e: errors.New(msg)}
return nil
})
defer failureBody.Release()
go r.b.Call("arrayBuffer").Call("then", successBody, failureBody)
r = <-ch
return r.r, r.e
}
// oof.
func mapOpts(opts *Opts) (map[string]interface{}, error) {
mp := map[string]interface{}{}
if opts.Method != "" {
mp["method"] = opts.Method
}
if opts.Headers != nil {
mp["headers"] = mapHeaders(opts.Headers)
}
if opts.Mode != "" {
mp["mode"] = opts.Mode
}
if opts.Credentials != "" {
mp["credentials"] = opts.Credentials
}
if opts.Cache != "" {
mp["cache"] = opts.Cache
}
if opts.Redirect != "" {
mp["redirect"] = opts.Redirect
}
if opts.Referrer != "" {
mp["referrer"] = opts.Referrer
}
if opts.ReferrerPolicy != "" {
mp["referrerPolicy"] = opts.ReferrerPolicy
}
if opts.Integrity != "" {
mp["integrity"] = opts.Integrity
}
if opts.KeepAlive != nil {
mp["keepalive"] = *opts.KeepAlive
}
if opts.Body != nil {
var bts []byte
var err error
switch v := opts.Body.(type) {
case *bytes.Buffer:
bts = v.Bytes()
default:
bts, err = io.ReadAll(opts.Body)
}
if err != nil {
return nil, err
}
jsbody := js.Global().Get("Uint8Array").New(len(bts))
js.CopyBytesToJS(jsbody, bts)
mp["body"] = jsbody
}
return mp, nil
}
func mapHeaders(mp map[string]string) map[string]interface{} {
newMap := map[string]interface{}{}
for k, v := range mp {
newMap[k] = v
}
return newMap
}