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 // jsFetchMissing will be true if the Fetch API is not present in
45 // the browser globals.
46 var jsFetchMissing = js.Global().Get("fetch").IsUndefined()
48 // jsFetchDisabled controls whether the use of Fetch API is disabled.
49 // It's set to true when we detect we're running in Node.js, so that
50 // RoundTrip ends up talking over the same fake network the HTTP servers
51 // currently use in various tests and examples. See go.dev/issue/57613.
53 // TODO(go.dev/issue/60810): See if it's viable to test the Fetch API
55 var jsFetchDisabled = js.Global().Get("process").Type() == js.TypeObject &&
56 strings.HasPrefix(js.Global().Get("process").Get("argv0").String(), "node")
58 // Determine whether the JS runtime supports streaming request bodies.
59 // Courtesy: https://developer.chrome.com/articles/fetch-streaming-requests/#feature-detection
60 func supportsPostRequestStreams() bool {
61 requestOpt := js.Global().Get("Object").New()
62 requestBody := js.Global().Get("ReadableStream").New()
64 requestOpt.Set("method", "POST")
65 requestOpt.Set("body", requestBody)
67 // There is quite a dance required to define a getter if you do not have the { get property() { ... } }
68 // syntax available. However, it is possible:
69 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get#defining_a_getter_on_existing_objects_using_defineproperty
71 duplexGetterObj := js.Global().Get("Object").New()
72 duplexGetterFunc := js.FuncOf(func(this js.Value, args []js.Value) any {
76 defer duplexGetterFunc.Release()
77 duplexGetterObj.Set("get", duplexGetterFunc)
78 js.Global().Get("Object").Call("defineProperty", requestOpt, "duplex", duplexGetterObj)
80 // Slight difference here between the aforementioned example: Non-browser-based runtimes
81 // do not have a non-empty API Base URL (https://html.spec.whatwg.org/multipage/webappapis.html#api-base-url)
82 // so we have to supply a valid URL here.
83 requestObject := js.Global().Get("Request").New("https://www.example.org", requestOpt)
85 hasContentTypeHeader := requestObject.Get("headers").Call("has", "Content-Type").Bool()
87 return duplexCalled && !hasContentTypeHeader
90 // RoundTrip implements the RoundTripper interface using the WHATWG Fetch API.
91 func (t *Transport) RoundTrip(req *Request) (*Response, error) {
92 // The Transport has a documented contract that states that if the DialContext or
93 // DialTLSContext functions are set, they will be used to set up the connections.
94 // If they aren't set then the documented contract is to use Dial or DialTLS, even
95 // though they are deprecated. Therefore, if any of these are set, we should obey
96 // the contract and dial using the regular round-trip instead. Otherwise, we'll try
97 // to fall back on the Fetch API, unless it's not available.
98 if t.Dial != nil || t.DialContext != nil || t.DialTLS != nil || t.DialTLSContext != nil || jsFetchMissing || jsFetchDisabled {
99 return t.roundTrip(req)
102 ac := js.Global().Get("AbortController")
103 if !ac.IsUndefined() {
104 // Some browsers that support WASM don't necessarily support
105 // the AbortController. See
106 // https://developer.mozilla.org/en-US/docs/Web/API/AbortController#Browser_compatibility.
110 opt := js.Global().Get("Object").New()
111 // See https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch
112 // for options available.
113 opt.Set("method", req.Method)
114 opt.Set("credentials", "same-origin")
115 if h := req.Header.Get(jsFetchCreds); h != "" {
116 opt.Set("credentials", h)
117 req.Header.Del(jsFetchCreds)
119 if h := req.Header.Get(jsFetchMode); h != "" {
121 req.Header.Del(jsFetchMode)
123 if h := req.Header.Get(jsFetchRedirect); h != "" {
124 opt.Set("redirect", h)
125 req.Header.Del(jsFetchRedirect)
127 if !ac.IsUndefined() {
128 opt.Set("signal", ac.Get("signal"))
130 headers := js.Global().Get("Headers").New()
131 for key, values := range req.Header {
132 for _, value := range values {
133 headers.Call("append", key, value)
136 opt.Set("headers", headers)
138 var readableStreamStart, readableStreamPull, readableStreamCancel js.Func
140 if !supportsPostRequestStreams() {
141 body, err := io.ReadAll(req.Body)
143 req.Body.Close() // RoundTrip must always close the body, including on errors.
147 buf := uint8Array.New(len(body))
148 js.CopyBytesToJS(buf, body)
152 readableStreamCtorArg := js.Global().Get("Object").New()
153 readableStreamCtorArg.Set("type", "bytes")
154 readableStreamCtorArg.Set("autoAllocateChunkSize", t.writeBufferSize())
156 readableStreamPull = js.FuncOf(func(this js.Value, args []js.Value) any {
157 controller := args[0]
158 byobRequest := controller.Get("byobRequest")
159 if byobRequest.IsNull() {
160 controller.Call("close")
163 byobRequestView := byobRequest.Get("view")
165 bodyBuf := make([]byte, byobRequestView.Get("byteLength").Int())
166 readBytes, readErr := io.ReadFull(req.Body, bodyBuf)
168 buf := uint8Array.New(byobRequestView.Get("buffer"))
169 js.CopyBytesToJS(buf, bodyBuf)
170 byobRequest.Call("respond", readBytes)
173 if readErr == io.EOF || readErr == io.ErrUnexpectedEOF {
174 controller.Call("close")
175 } else if readErr != nil {
176 readErrCauseObject := js.Global().Get("Object").New()
177 readErrCauseObject.Set("cause", readErr.Error())
178 readErr := js.Global().Get("Error").New("io.ReadFull failed while streaming POST body", readErrCauseObject)
179 controller.Call("error", readErr)
181 // Note: This a return from the pull callback of the controller and *not* RoundTrip().
184 readableStreamCtorArg.Set("pull", readableStreamPull)
186 opt.Set("body", js.Global().Get("ReadableStream").New(readableStreamCtorArg))
187 // There is a requirement from the WHATWG fetch standard that the duplex property of
188 // the object given as the options argument to the fetch call be set to 'half'
189 // when the body property of the same options object is a ReadableStream:
190 // https://fetch.spec.whatwg.org/#dom-requestinit-duplex
191 opt.Set("duplex", "half")
195 fetchPromise := js.Global().Call("fetch", req.URL.String(), opt)
197 respCh = make(chan *Response, 1)
198 errCh = make(chan error, 1)
199 success, failure js.Func
201 success = js.FuncOf(func(this js.Value, args []js.Value) any {
204 readableStreamCancel.Release()
205 readableStreamPull.Release()
206 readableStreamStart.Release()
212 // https://developer.mozilla.org/en-US/docs/Web/API/Headers/entries
213 headersIt := result.Get("headers").Call("entries")
215 n := headersIt.Call("next")
216 if n.Get("done").Bool() {
219 pair := n.Get("value")
220 key, value := pair.Index(0).String(), pair.Index(1).String()
221 ck := CanonicalHeaderKey(key)
222 header[ck] = append(header[ck], value)
225 contentLength := int64(0)
226 clHeader := header.Get("Content-Length")
229 cl, err := strconv.ParseInt(clHeader, 10, 64)
231 errCh <- fmt.Errorf("net/http: ill-formed Content-Length header: %v", err)
235 // Content-Length values less than 0 are invalid.
236 // See: https://datatracker.ietf.org/doc/html/rfc2616/#section-14.13
237 errCh <- fmt.Errorf("net/http: invalid Content-Length header: %q", clHeader)
242 // If the response length is not declared, set it to -1.
246 b := result.Get("body")
247 var body io.ReadCloser
248 // The body is undefined when the browser does not support streaming response bodies (Firefox),
249 // and null in certain error cases, i.e. when the request is blocked because of CORS settings.
250 if !b.IsUndefined() && !b.IsNull() {
251 body = &streamReader{stream: b.Call("getReader")}
253 // Fall back to using ArrayBuffer
254 // https://developer.mozilla.org/en-US/docs/Web/API/Body/arrayBuffer
255 body = &arrayReader{arrayPromise: result.Call("arrayBuffer")}
258 code := result.Get("status").Int()
260 Status: fmt.Sprintf("%d %s", code, StatusText(code)),
263 ContentLength: contentLength,
270 failure = js.FuncOf(func(this js.Value, args []js.Value) any {
273 readableStreamCancel.Release()
274 readableStreamPull.Release()
275 readableStreamStart.Release()
280 // The error is a JS Error type
281 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error
282 // We can use the toString() method to get a string representation of the error.
283 errMsg := err.Call("toString").String()
284 // Errors can optionally contain a cause.
285 if cause := err.Get("cause"); !cause.IsUndefined() {
286 // The exact type of the cause is not defined,
287 // but if it's another error, we can call toString() on it too.
288 if !cause.Get("toString").IsUndefined() {
289 errMsg += ": " + cause.Call("toString").String()
290 } else if cause.Type() == js.TypeString {
291 errMsg += ": " + cause.String()
294 errCh <- fmt.Errorf("net/http: fetch() failed: %s", errMsg)
298 fetchPromise.Call("then", success, failure)
300 case <-req.Context().Done():
301 if !ac.IsUndefined() {
302 // Abort the Fetch request.
305 return nil, req.Context().Err()
306 case resp := <-respCh:
313 var errClosed = errors.New("net/http: reader is closed")
315 // streamReader implements an io.ReadCloser wrapper for ReadableStream.
316 // See https://fetch.spec.whatwg.org/#readablestream for more information.
317 type streamReader struct {
320 err error // sticky read error
323 func (r *streamReader) Read(p []byte) (n int, err error) {
327 if len(r.pending) == 0 {
329 bCh = make(chan []byte, 1)
330 errCh = make(chan error, 1)
332 success := js.FuncOf(func(this js.Value, args []js.Value) any {
334 if result.Get("done").Bool() {
338 value := make([]byte, result.Get("value").Get("byteLength").Int())
339 js.CopyBytesToGo(value, result.Get("value"))
343 defer success.Release()
344 failure := js.FuncOf(func(this js.Value, args []js.Value) any {
345 // Assumes it's a TypeError. See
346 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError
347 // for more information on this type. See
348 // https://streams.spec.whatwg.org/#byob-reader-read for the spec on
350 errCh <- errors.New(args[0].Get("message").String())
353 defer failure.Release()
354 r.stream.Call("read").Call("then", success, failure)
363 n = copy(p, r.pending)
364 r.pending = r.pending[n:]
368 func (r *streamReader) Close() error {
369 // This ignores any error returned from cancel method. So far, I did not encounter any concrete
370 // situation where reporting the error is meaningful. Most users ignore error from resp.Body.Close().
371 // If there's a need to report error here, it can be implemented and tested when that need comes up.
372 r.stream.Call("cancel")
379 // arrayReader implements an io.ReadCloser wrapper for ArrayBuffer.
380 // https://developer.mozilla.org/en-US/docs/Web/API/Body/arrayBuffer.
381 type arrayReader struct {
382 arrayPromise js.Value
385 err error // sticky read error
388 func (r *arrayReader) Read(p []byte) (n int, err error) {
395 bCh = make(chan []byte, 1)
396 errCh = make(chan error, 1)
398 success := js.FuncOf(func(this js.Value, args []js.Value) any {
399 // Wrap the input ArrayBuffer with a Uint8Array
400 uint8arrayWrapper := uint8Array.New(args[0])
401 value := make([]byte, uint8arrayWrapper.Get("byteLength").Int())
402 js.CopyBytesToGo(value, uint8arrayWrapper)
406 defer success.Release()
407 failure := js.FuncOf(func(this js.Value, args []js.Value) any {
408 // Assumes it's a TypeError. See
409 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError
410 // for more information on this type.
411 // See https://fetch.spec.whatwg.org/#concept-body-consume-body for reasons this might error.
412 errCh <- errors.New(args[0].Get("message").String())
415 defer failure.Release()
416 r.arrayPromise.Call("then", success, failure)
424 if len(r.pending) == 0 {
427 n = copy(p, r.pending)
428 r.pending = r.pending[n:]
432 func (r *arrayReader) Close() error {