1 // Copyright 2018 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
18 var uint8Array = js.Global().Get("Uint8Array")
20 // jsFetchMode is a Request.Header map key that, if present,
21 // signals that the map entry is actually an option to the Fetch API mode setting.
22 // Valid values are: "cors", "no-cors", "same-origin", "navigate"
23 // The default is "same-origin".
25 // Reference: https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters
26 const jsFetchMode = "js.fetch:mode"
28 // jsFetchCreds is a Request.Header map key that, if present,
29 // signals that the map entry is actually an option to the Fetch API credentials setting.
30 // Valid values are: "omit", "same-origin", "include"
31 // The default is "same-origin".
33 // Reference: https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters
34 const jsFetchCreds = "js.fetch:credentials"
36 // jsFetchRedirect is a Request.Header map key that, if present,
37 // signals that the map entry is actually an option to the Fetch API redirect setting.
38 // Valid values are: "follow", "error", "manual"
39 // The default is "follow".
41 // Reference: https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters
42 const jsFetchRedirect = "js.fetch:redirect"
44 var useFakeNetwork = js.Global().Get("fetch").IsUndefined()
46 // RoundTrip implements the RoundTripper interface using the WHATWG Fetch API.
47 func (t *Transport) RoundTrip(req *Request) (*Response, error) {
49 return t.roundTrip(req)
52 ac := js.Global().Get("AbortController")
53 if !ac.IsUndefined() {
54 // Some browsers that support WASM don't necessarily support
55 // the AbortController. See
56 // https://developer.mozilla.org/en-US/docs/Web/API/AbortController#Browser_compatibility.
60 opt := js.Global().Get("Object").New()
61 // See https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch
62 // for options available.
63 opt.Set("method", req.Method)
64 opt.Set("credentials", "same-origin")
65 if h := req.Header.Get(jsFetchCreds); h != "" {
66 opt.Set("credentials", h)
67 req.Header.Del(jsFetchCreds)
69 if h := req.Header.Get(jsFetchMode); h != "" {
71 req.Header.Del(jsFetchMode)
73 if h := req.Header.Get(jsFetchRedirect); h != "" {
74 opt.Set("redirect", h)
75 req.Header.Del(jsFetchRedirect)
77 if !ac.IsUndefined() {
78 opt.Set("signal", ac.Get("signal"))
80 headers := js.Global().Get("Headers").New()
81 for key, values := range req.Header {
82 for _, value := range values {
83 headers.Call("append", key, value)
86 opt.Set("headers", headers)
89 // TODO(johanbrandhorst): Stream request body when possible.
90 // See https://bugs.chromium.org/p/chromium/issues/detail?id=688906 for Blink issue.
91 // See https://bugzilla.mozilla.org/show_bug.cgi?id=1387483 for Firefox issue.
92 // See https://github.com/web-platform-tests/wpt/issues/7693 for WHATWG tests issue.
93 // See https://developer.mozilla.org/en-US/docs/Web/API/Streams_API for more details on the Streams API
94 // and browser support.
95 body, err := io.ReadAll(req.Body)
97 req.Body.Close() // RoundTrip must always close the body, including on errors.
102 buf := uint8Array.New(len(body))
103 js.CopyBytesToJS(buf, body)
108 fetchPromise := js.Global().Call("fetch", req.URL.String(), opt)
110 respCh = make(chan *Response, 1)
111 errCh = make(chan error, 1)
112 success, failure js.Func
114 success = js.FuncOf(func(this js.Value, args []js.Value) interface{} {
120 // https://developer.mozilla.org/en-US/docs/Web/API/Headers/entries
121 headersIt := result.Get("headers").Call("entries")
123 n := headersIt.Call("next")
124 if n.Get("done").Bool() {
127 pair := n.Get("value")
128 key, value := pair.Index(0).String(), pair.Index(1).String()
129 ck := CanonicalHeaderKey(key)
130 header[ck] = append(header[ck], value)
133 contentLength := int64(0)
134 if cl, err := strconv.ParseInt(header.Get("Content-Length"), 10, 64); err == nil {
138 b := result.Get("body")
139 var body io.ReadCloser
140 // The body is undefined when the browser does not support streaming response bodies (Firefox),
141 // and null in certain error cases, i.e. when the request is blocked because of CORS settings.
142 if !b.IsUndefined() && !b.IsNull() {
143 body = &streamReader{stream: b.Call("getReader")}
145 // Fall back to using ArrayBuffer
146 // https://developer.mozilla.org/en-US/docs/Web/API/Body/arrayBuffer
147 body = &arrayReader{arrayPromise: result.Call("arrayBuffer")}
150 code := result.Get("status").Int()
152 Status: fmt.Sprintf("%d %s", code, StatusText(code)),
155 ContentLength: contentLength,
162 failure = js.FuncOf(func(this js.Value, args []js.Value) interface{} {
165 errCh <- fmt.Errorf("net/http: fetch() failed: %s", args[0].Get("message").String())
169 fetchPromise.Call("then", success, failure)
171 case <-req.Context().Done():
172 if !ac.IsUndefined() {
173 // Abort the Fetch request.
176 return nil, req.Context().Err()
177 case resp := <-respCh:
184 var errClosed = errors.New("net/http: reader is closed")
186 // streamReader implements an io.ReadCloser wrapper for ReadableStream.
187 // See https://fetch.spec.whatwg.org/#readablestream for more information.
188 type streamReader struct {
191 err error // sticky read error
194 func (r *streamReader) Read(p []byte) (n int, err error) {
198 if len(r.pending) == 0 {
200 bCh = make(chan []byte, 1)
201 errCh = make(chan error, 1)
203 success := js.FuncOf(func(this js.Value, args []js.Value) interface{} {
205 if result.Get("done").Bool() {
209 value := make([]byte, result.Get("value").Get("byteLength").Int())
210 js.CopyBytesToGo(value, result.Get("value"))
214 defer success.Release()
215 failure := js.FuncOf(func(this js.Value, args []js.Value) interface{} {
216 // Assumes it's a TypeError. See
217 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError
218 // for more information on this type. See
219 // https://streams.spec.whatwg.org/#byob-reader-read for the spec on
221 errCh <- errors.New(args[0].Get("message").String())
224 defer failure.Release()
225 r.stream.Call("read").Call("then", success, failure)
234 n = copy(p, r.pending)
235 r.pending = r.pending[n:]
239 func (r *streamReader) Close() error {
240 // This ignores any error returned from cancel method. So far, I did not encounter any concrete
241 // situation where reporting the error is meaningful. Most users ignore error from resp.Body.Close().
242 // If there's a need to report error here, it can be implemented and tested when that need comes up.
243 r.stream.Call("cancel")
250 // arrayReader implements an io.ReadCloser wrapper for ArrayBuffer.
251 // https://developer.mozilla.org/en-US/docs/Web/API/Body/arrayBuffer.
252 type arrayReader struct {
253 arrayPromise js.Value
256 err error // sticky read error
259 func (r *arrayReader) Read(p []byte) (n int, err error) {
266 bCh = make(chan []byte, 1)
267 errCh = make(chan error, 1)
269 success := js.FuncOf(func(this js.Value, args []js.Value) interface{} {
270 // Wrap the input ArrayBuffer with a Uint8Array
271 uint8arrayWrapper := uint8Array.New(args[0])
272 value := make([]byte, uint8arrayWrapper.Get("byteLength").Int())
273 js.CopyBytesToGo(value, uint8arrayWrapper)
277 defer success.Release()
278 failure := js.FuncOf(func(this js.Value, args []js.Value) interface{} {
279 // Assumes it's a TypeError. See
280 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError
281 // for more information on this type.
282 // See https://fetch.spec.whatwg.org/#concept-body-consume-body for reasons this might error.
283 errCh <- errors.New(args[0].Get("message").String())
286 defer failure.Release()
287 r.arrayPromise.Call("then", success, failure)
295 if len(r.pending) == 0 {
298 n = copy(p, r.pending)
299 r.pending = r.pending[n:]
303 func (r *arrayReader) Close() error {