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.
17 var uint8Array = js.Global().Get("Uint8Array")
19 // jsFetchMode is a Request.Header map key that, if present,
20 // signals that the map entry is actually an option to the Fetch API mode setting.
21 // Valid values are: "cors", "no-cors", "same-origin", "navigate"
22 // The default is "same-origin".
24 // Reference: https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters
25 const jsFetchMode = "js.fetch:mode"
27 // jsFetchCreds is a Request.Header map key that, if present,
28 // signals that the map entry is actually an option to the Fetch API credentials setting.
29 // Valid values are: "omit", "same-origin", "include"
30 // The default is "same-origin".
32 // Reference: https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters
33 const jsFetchCreds = "js.fetch:credentials"
35 // jsFetchRedirect is a Request.Header map key that, if present,
36 // signals that the map entry is actually an option to the Fetch API redirect setting.
37 // Valid values are: "follow", "error", "manual"
38 // The default is "follow".
40 // Reference: https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters
41 const jsFetchRedirect = "js.fetch:redirect"
43 var useFakeNetwork = js.Global().Get("fetch").IsUndefined()
45 // RoundTrip implements the RoundTripper interface using the WHATWG Fetch API.
46 func (t *Transport) RoundTrip(req *Request) (*Response, error) {
48 return t.roundTrip(req)
51 ac := js.Global().Get("AbortController")
52 if !ac.IsUndefined() {
53 // Some browsers that support WASM don't necessarily support
54 // the AbortController. See
55 // https://developer.mozilla.org/en-US/docs/Web/API/AbortController#Browser_compatibility.
59 opt := js.Global().Get("Object").New()
60 // See https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch
61 // for options available.
62 opt.Set("method", req.Method)
63 opt.Set("credentials", "same-origin")
64 if h := req.Header.Get(jsFetchCreds); h != "" {
65 opt.Set("credentials", h)
66 req.Header.Del(jsFetchCreds)
68 if h := req.Header.Get(jsFetchMode); h != "" {
70 req.Header.Del(jsFetchMode)
72 if h := req.Header.Get(jsFetchRedirect); h != "" {
73 opt.Set("redirect", h)
74 req.Header.Del(jsFetchRedirect)
76 if !ac.IsUndefined() {
77 opt.Set("signal", ac.Get("signal"))
79 headers := js.Global().Get("Headers").New()
80 for key, values := range req.Header {
81 for _, value := range values {
82 headers.Call("append", key, value)
85 opt.Set("headers", headers)
88 // TODO(johanbrandhorst): Stream request body when possible.
89 // See https://bugs.chromium.org/p/chromium/issues/detail?id=688906 for Blink issue.
90 // See https://bugzilla.mozilla.org/show_bug.cgi?id=1387483 for Firefox issue.
91 // See https://github.com/web-platform-tests/wpt/issues/7693 for WHATWG tests issue.
92 // See https://developer.mozilla.org/en-US/docs/Web/API/Streams_API for more details on the Streams API
93 // and browser support.
94 body, err := io.ReadAll(req.Body)
96 req.Body.Close() // RoundTrip must always close the body, including on errors.
101 buf := uint8Array.New(len(body))
102 js.CopyBytesToJS(buf, body)
107 fetchPromise := js.Global().Call("fetch", req.URL.String(), opt)
109 respCh = make(chan *Response, 1)
110 errCh = make(chan error, 1)
111 success, failure js.Func
113 success = js.FuncOf(func(this js.Value, args []js.Value) interface{} {
119 // https://developer.mozilla.org/en-US/docs/Web/API/Headers/entries
120 headersIt := result.Get("headers").Call("entries")
122 n := headersIt.Call("next")
123 if n.Get("done").Bool() {
126 pair := n.Get("value")
127 key, value := pair.Index(0).String(), pair.Index(1).String()
128 ck := CanonicalHeaderKey(key)
129 header[ck] = append(header[ck], value)
132 contentLength := int64(0)
133 if cl, err := strconv.ParseInt(header.Get("Content-Length"), 10, 64); err == nil {
137 b := result.Get("body")
138 var body io.ReadCloser
139 // The body is undefined when the browser does not support streaming response bodies (Firefox),
140 // and null in certain error cases, i.e. when the request is blocked because of CORS settings.
141 if !b.IsUndefined() && !b.IsNull() {
142 body = &streamReader{stream: b.Call("getReader")}
144 // Fall back to using ArrayBuffer
145 // https://developer.mozilla.org/en-US/docs/Web/API/Body/arrayBuffer
146 body = &arrayReader{arrayPromise: result.Call("arrayBuffer")}
149 code := result.Get("status").Int()
151 Status: fmt.Sprintf("%d %s", code, StatusText(code)),
154 ContentLength: contentLength,
161 failure = js.FuncOf(func(this js.Value, args []js.Value) interface{} {
164 errCh <- fmt.Errorf("net/http: fetch() failed: %s", args[0].Get("message").String())
168 fetchPromise.Call("then", success, failure)
170 case <-req.Context().Done():
171 if !ac.IsUndefined() {
172 // Abort the Fetch request.
175 return nil, req.Context().Err()
176 case resp := <-respCh:
183 var errClosed = errors.New("net/http: reader is closed")
185 // streamReader implements an io.ReadCloser wrapper for ReadableStream.
186 // See https://fetch.spec.whatwg.org/#readablestream for more information.
187 type streamReader struct {
190 err error // sticky read error
193 func (r *streamReader) Read(p []byte) (n int, err error) {
197 if len(r.pending) == 0 {
199 bCh = make(chan []byte, 1)
200 errCh = make(chan error, 1)
202 success := js.FuncOf(func(this js.Value, args []js.Value) interface{} {
204 if result.Get("done").Bool() {
208 value := make([]byte, result.Get("value").Get("byteLength").Int())
209 js.CopyBytesToGo(value, result.Get("value"))
213 defer success.Release()
214 failure := js.FuncOf(func(this js.Value, args []js.Value) interface{} {
215 // Assumes it's a TypeError. See
216 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError
217 // for more information on this type. See
218 // https://streams.spec.whatwg.org/#byob-reader-read for the spec on
220 errCh <- errors.New(args[0].Get("message").String())
223 defer failure.Release()
224 r.stream.Call("read").Call("then", success, failure)
233 n = copy(p, r.pending)
234 r.pending = r.pending[n:]
238 func (r *streamReader) Close() error {
239 // This ignores any error returned from cancel method. So far, I did not encounter any concrete
240 // situation where reporting the error is meaningful. Most users ignore error from resp.Body.Close().
241 // If there's a need to report error here, it can be implemented and tested when that need comes up.
242 r.stream.Call("cancel")
249 // arrayReader implements an io.ReadCloser wrapper for ArrayBuffer.
250 // https://developer.mozilla.org/en-US/docs/Web/API/Body/arrayBuffer.
251 type arrayReader struct {
252 arrayPromise js.Value
255 err error // sticky read error
258 func (r *arrayReader) Read(p []byte) (n int, err error) {
265 bCh = make(chan []byte, 1)
266 errCh = make(chan error, 1)
268 success := js.FuncOf(func(this js.Value, args []js.Value) interface{} {
269 // Wrap the input ArrayBuffer with a Uint8Array
270 uint8arrayWrapper := uint8Array.New(args[0])
271 value := make([]byte, uint8arrayWrapper.Get("byteLength").Int())
272 js.CopyBytesToGo(value, uint8arrayWrapper)
276 defer success.Release()
277 failure := js.FuncOf(func(this js.Value, args []js.Value) interface{} {
278 // Assumes it's a TypeError. See
279 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError
280 // for more information on this type.
281 // See https://fetch.spec.whatwg.org/#concept-body-consume-body for reasons this might error.
282 errCh <- errors.New(args[0].Get("message").String())
285 defer failure.Release()
286 r.arrayPromise.Call("then", success, failure)
294 if len(r.pending) == 0 {
297 n = copy(p, r.pending)
298 r.pending = r.pending[n:]
302 func (r *arrayReader) Close() error {