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 // RoundTrip implements the RoundTripper interface using the WHATWG Fetch API.
49 func (t *Transport) RoundTrip(req *Request) (*Response, error) {
50 // The Transport has a documented contract that states that if the DialContext or
51 // DialTLSContext functions are set, they will be used to set up the connections.
52 // If they aren't set then the documented contract is to use Dial or DialTLS, even
53 // though they are deprecated. Therefore, if any of these are set, we should obey
54 // the contract and dial using the regular round-trip instead. Otherwise, we'll try
55 // to fall back on the Fetch API, unless it's not available.
56 if t.Dial != nil || t.DialContext != nil || t.DialTLS != nil || t.DialTLSContext != nil || jsFetchMissing {
57 return t.roundTrip(req)
60 ac := js.Global().Get("AbortController")
61 if !ac.IsUndefined() {
62 // Some browsers that support WASM don't necessarily support
63 // the AbortController. See
64 // https://developer.mozilla.org/en-US/docs/Web/API/AbortController#Browser_compatibility.
68 opt := js.Global().Get("Object").New()
69 // See https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch
70 // for options available.
71 opt.Set("method", req.Method)
72 opt.Set("credentials", "same-origin")
73 if h := req.Header.Get(jsFetchCreds); h != "" {
74 opt.Set("credentials", h)
75 req.Header.Del(jsFetchCreds)
77 if h := req.Header.Get(jsFetchMode); h != "" {
79 req.Header.Del(jsFetchMode)
81 if h := req.Header.Get(jsFetchRedirect); h != "" {
82 opt.Set("redirect", h)
83 req.Header.Del(jsFetchRedirect)
85 if !ac.IsUndefined() {
86 opt.Set("signal", ac.Get("signal"))
88 headers := js.Global().Get("Headers").New()
89 for key, values := range req.Header {
90 for _, value := range values {
91 headers.Call("append", key, value)
94 opt.Set("headers", headers)
97 // TODO(johanbrandhorst): Stream request body when possible.
98 // See https://bugs.chromium.org/p/chromium/issues/detail?id=688906 for Blink issue.
99 // See https://bugzilla.mozilla.org/show_bug.cgi?id=1387483 for Firefox issue.
100 // See https://github.com/web-platform-tests/wpt/issues/7693 for WHATWG tests issue.
101 // See https://developer.mozilla.org/en-US/docs/Web/API/Streams_API for more details on the Streams API
102 // and browser support.
103 body, err := io.ReadAll(req.Body)
105 req.Body.Close() // RoundTrip must always close the body, including on errors.
110 buf := uint8Array.New(len(body))
111 js.CopyBytesToJS(buf, body)
116 fetchPromise := js.Global().Call("fetch", req.URL.String(), opt)
118 respCh = make(chan *Response, 1)
119 errCh = make(chan error, 1)
120 success, failure js.Func
122 success = js.FuncOf(func(this js.Value, args []js.Value) interface{} {
128 // https://developer.mozilla.org/en-US/docs/Web/API/Headers/entries
129 headersIt := result.Get("headers").Call("entries")
131 n := headersIt.Call("next")
132 if n.Get("done").Bool() {
135 pair := n.Get("value")
136 key, value := pair.Index(0).String(), pair.Index(1).String()
137 ck := CanonicalHeaderKey(key)
138 header[ck] = append(header[ck], value)
141 contentLength := int64(0)
142 clHeader := header.Get("Content-Length")
145 cl, err := strconv.ParseInt(clHeader, 10, 64)
147 errCh <- fmt.Errorf("net/http: ill-formed Content-Length header: %v", err)
151 // Content-Length values less than 0 are invalid.
152 // See: https://datatracker.ietf.org/doc/html/rfc2616/#section-14.13
153 errCh <- fmt.Errorf("net/http: invalid Content-Length header: %q", clHeader)
158 // If the response length is not declared, set it to -1.
162 b := result.Get("body")
163 var body io.ReadCloser
164 // The body is undefined when the browser does not support streaming response bodies (Firefox),
165 // and null in certain error cases, i.e. when the request is blocked because of CORS settings.
166 if !b.IsUndefined() && !b.IsNull() {
167 body = &streamReader{stream: b.Call("getReader")}
169 // Fall back to using ArrayBuffer
170 // https://developer.mozilla.org/en-US/docs/Web/API/Body/arrayBuffer
171 body = &arrayReader{arrayPromise: result.Call("arrayBuffer")}
174 code := result.Get("status").Int()
176 Status: fmt.Sprintf("%d %s", code, StatusText(code)),
179 ContentLength: contentLength,
186 failure = js.FuncOf(func(this js.Value, args []js.Value) interface{} {
189 errCh <- fmt.Errorf("net/http: fetch() failed: %s", args[0].Get("message").String())
193 fetchPromise.Call("then", success, failure)
195 case <-req.Context().Done():
196 if !ac.IsUndefined() {
197 // Abort the Fetch request.
200 return nil, req.Context().Err()
201 case resp := <-respCh:
208 var errClosed = errors.New("net/http: reader is closed")
210 // streamReader implements an io.ReadCloser wrapper for ReadableStream.
211 // See https://fetch.spec.whatwg.org/#readablestream for more information.
212 type streamReader struct {
215 err error // sticky read error
218 func (r *streamReader) Read(p []byte) (n int, err error) {
222 if len(r.pending) == 0 {
224 bCh = make(chan []byte, 1)
225 errCh = make(chan error, 1)
227 success := js.FuncOf(func(this js.Value, args []js.Value) interface{} {
229 if result.Get("done").Bool() {
233 value := make([]byte, result.Get("value").Get("byteLength").Int())
234 js.CopyBytesToGo(value, result.Get("value"))
238 defer success.Release()
239 failure := js.FuncOf(func(this js.Value, args []js.Value) interface{} {
240 // Assumes it's a TypeError. See
241 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError
242 // for more information on this type. See
243 // https://streams.spec.whatwg.org/#byob-reader-read for the spec on
245 errCh <- errors.New(args[0].Get("message").String())
248 defer failure.Release()
249 r.stream.Call("read").Call("then", success, failure)
258 n = copy(p, r.pending)
259 r.pending = r.pending[n:]
263 func (r *streamReader) Close() error {
264 // This ignores any error returned from cancel method. So far, I did not encounter any concrete
265 // situation where reporting the error is meaningful. Most users ignore error from resp.Body.Close().
266 // If there's a need to report error here, it can be implemented and tested when that need comes up.
267 r.stream.Call("cancel")
274 // arrayReader implements an io.ReadCloser wrapper for ArrayBuffer.
275 // https://developer.mozilla.org/en-US/docs/Web/API/Body/arrayBuffer.
276 type arrayReader struct {
277 arrayPromise js.Value
280 err error // sticky read error
283 func (r *arrayReader) Read(p []byte) (n int, err error) {
290 bCh = make(chan []byte, 1)
291 errCh = make(chan error, 1)
293 success := js.FuncOf(func(this js.Value, args []js.Value) interface{} {
294 // Wrap the input ArrayBuffer with a Uint8Array
295 uint8arrayWrapper := uint8Array.New(args[0])
296 value := make([]byte, uint8arrayWrapper.Get("byteLength").Int())
297 js.CopyBytesToGo(value, uint8arrayWrapper)
301 defer success.Release()
302 failure := js.FuncOf(func(this js.Value, args []js.Value) interface{} {
303 // Assumes it's a TypeError. See
304 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError
305 // for more information on this type.
306 // See https://fetch.spec.whatwg.org/#concept-body-consume-body for reasons this might error.
307 errCh <- errors.New(args[0].Get("message").String())
310 defer failure.Release()
311 r.arrayPromise.Call("then", success, failure)
319 if len(r.pending) == 0 {
322 n = copy(p, r.pending)
323 r.pending = r.pending[n:]
327 func (r *arrayReader) Close() error {