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.
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 // RoundTrip implements the RoundTripper interface using the WHATWG Fetch API.
37 func (t *Transport) RoundTrip(req *Request) (*Response, error) {
39 return t.roundTrip(req)
42 ac := js.Global().Get("AbortController")
43 if ac != js.Undefined() {
44 // Some browsers that support WASM don't necessarily support
45 // the AbortController. See
46 // https://developer.mozilla.org/en-US/docs/Web/API/AbortController#Browser_compatibility.
50 opt := js.Global().Get("Object").New()
51 // See https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch
52 // for options available.
53 opt.Set("method", req.Method)
54 opt.Set("credentials", "same-origin")
55 if h := req.Header.Get(jsFetchCreds); h != "" {
56 opt.Set("credentials", h)
57 req.Header.Del(jsFetchCreds)
59 if h := req.Header.Get(jsFetchMode); h != "" {
61 req.Header.Del(jsFetchMode)
63 if ac != js.Undefined() {
64 opt.Set("signal", ac.Get("signal"))
66 headers := js.Global().Get("Headers").New()
67 for key, values := range req.Header {
68 for _, value := range values {
69 headers.Call("append", key, value)
72 opt.Set("headers", headers)
75 // TODO(johanbrandhorst): Stream request body when possible.
76 // See https://bugs.chromium.org/p/chromium/issues/detail?id=688906 for Blink issue.
77 // See https://bugzilla.mozilla.org/show_bug.cgi?id=1387483 for Firefox issue.
78 // See https://github.com/web-platform-tests/wpt/issues/7693 for WHATWG tests issue.
79 // See https://developer.mozilla.org/en-US/docs/Web/API/Streams_API for more details on the Streams API
80 // and browser support.
81 body, err := ioutil.ReadAll(req.Body)
83 req.Body.Close() // RoundTrip must always close the body, including on errors.
87 a := js.TypedArrayOf(body)
91 respPromise := js.Global().Call("fetch", req.URL.String(), opt)
93 respCh = make(chan *Response, 1)
94 errCh = make(chan error, 1)
96 success := js.FuncOf(func(this js.Value, args []js.Value) interface{} {
99 // https://developer.mozilla.org/en-US/docs/Web/API/Headers/entries
100 headersIt := result.Get("headers").Call("entries")
102 n := headersIt.Call("next")
103 if n.Get("done").Bool() {
106 pair := n.Get("value")
107 key, value := pair.Index(0).String(), pair.Index(1).String()
108 ck := CanonicalHeaderKey(key)
109 header[ck] = append(header[ck], value)
112 contentLength := int64(0)
113 if cl, err := strconv.ParseInt(header.Get("Content-Length"), 10, 64); err == nil {
117 b := result.Get("body")
118 var body io.ReadCloser
119 // The body is undefined when the browser does not support streaming response bodies (Firefox),
120 // and null in certain error cases, i.e. when the request is blocked because of CORS settings.
121 if b != js.Undefined() && b != js.Null() {
122 body = &streamReader{stream: b.Call("getReader")}
124 // Fall back to using ArrayBuffer
125 // https://developer.mozilla.org/en-US/docs/Web/API/Body/arrayBuffer
126 body = &arrayReader{arrayPromise: result.Call("arrayBuffer")}
130 case respCh <- &Response{
131 Status: result.Get("status").String() + " " + StatusText(result.Get("status").Int()),
132 StatusCode: result.Get("status").Int(),
134 ContentLength: contentLength,
138 case <-req.Context().Done():
143 defer success.Release()
144 failure := js.FuncOf(func(this js.Value, args []js.Value) interface{} {
145 err := fmt.Errorf("net/http: fetch() failed: %s", args[0].String())
148 case <-req.Context().Done():
152 defer failure.Release()
153 respPromise.Call("then", success, failure)
155 case <-req.Context().Done():
156 if ac != js.Undefined() {
157 // Abort the Fetch request
160 return nil, req.Context().Err()
161 case resp := <-respCh:
168 var errClosed = errors.New("net/http: reader is closed")
170 // useFakeNetwork is used to determine whether the request is made
171 // by a test and should be made to use the fake in-memory network.
172 func useFakeNetwork() bool {
173 return len(os.Args) > 0 && strings.HasSuffix(os.Args[0], ".test")
176 // streamReader implements an io.ReadCloser wrapper for ReadableStream.
177 // See https://fetch.spec.whatwg.org/#readablestream for more information.
178 type streamReader struct {
181 err error // sticky read error
184 func (r *streamReader) Read(p []byte) (n int, err error) {
188 if len(r.pending) == 0 {
190 bCh = make(chan []byte, 1)
191 errCh = make(chan error, 1)
193 success := js.FuncOf(func(this js.Value, args []js.Value) interface{} {
195 if result.Get("done").Bool() {
199 value := make([]byte, result.Get("value").Get("byteLength").Int())
200 a := js.TypedArrayOf(value)
201 a.Call("set", result.Get("value"))
206 defer success.Release()
207 failure := js.FuncOf(func(this js.Value, args []js.Value) interface{} {
208 // Assumes it's a TypeError. See
209 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError
210 // for more information on this type. See
211 // https://streams.spec.whatwg.org/#byob-reader-read for the spec on
213 errCh <- errors.New(args[0].Get("message").String())
216 defer failure.Release()
217 r.stream.Call("read").Call("then", success, failure)
226 n = copy(p, r.pending)
227 r.pending = r.pending[n:]
231 func (r *streamReader) Close() error {
232 // This ignores any error returned from cancel method. So far, I did not encounter any concrete
233 // situation where reporting the error is meaningful. Most users ignore error from resp.Body.Close().
234 // If there's a need to report error here, it can be implemented and tested when that need comes up.
235 r.stream.Call("cancel")
242 // arrayReader implements an io.ReadCloser wrapper for ArrayBuffer.
243 // https://developer.mozilla.org/en-US/docs/Web/API/Body/arrayBuffer.
244 type arrayReader struct {
245 arrayPromise js.Value
248 err error // sticky read error
251 func (r *arrayReader) Read(p []byte) (n int, err error) {
258 bCh = make(chan []byte, 1)
259 errCh = make(chan error, 1)
261 success := js.FuncOf(func(this js.Value, args []js.Value) interface{} {
262 // Wrap the input ArrayBuffer with a Uint8Array
263 uint8arrayWrapper := js.Global().Get("Uint8Array").New(args[0])
264 value := make([]byte, uint8arrayWrapper.Get("byteLength").Int())
265 a := js.TypedArrayOf(value)
266 a.Call("set", uint8arrayWrapper)
271 defer success.Release()
272 failure := js.FuncOf(func(this js.Value, args []js.Value) interface{} {
273 // Assumes it's a TypeError. See
274 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError
275 // for more information on this type.
276 // See https://fetch.spec.whatwg.org/#concept-body-consume-body for reasons this might error.
277 errCh <- errors.New(args[0].Get("message").String())
280 defer failure.Release()
281 r.arrayPromise.Call("then", success, failure)
289 if len(r.pending) == 0 {
292 n = copy(p, r.pending)
293 r.pending = r.pending[n:]
297 func (r *arrayReader) Close() error {