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 // RoundTrip implements the RoundTripper interface using the WHATWG Fetch API.
21 func (t *Transport) RoundTrip(req *Request) (*Response, error) {
23 return t.roundTrip(req)
25 headers := js.Global().Get("Headers").New()
26 for key, values := range req.Header {
27 for _, value := range values {
28 headers.Call("append", key, value)
32 ac := js.Global().Get("AbortController")
33 if ac != js.Undefined() {
34 // Some browsers that support WASM don't necessarily support
35 // the AbortController. See
36 // https://developer.mozilla.org/en-US/docs/Web/API/AbortController#Browser_compatibility.
40 opt := js.Global().Get("Object").New()
41 // See https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch
42 // for options available.
43 opt.Set("headers", headers)
44 opt.Set("method", req.Method)
45 opt.Set("credentials", "same-origin")
46 if ac != js.Undefined() {
47 opt.Set("signal", ac.Get("signal"))
51 // TODO(johanbrandhorst): Stream request body when possible.
52 // See https://bugs.chromium.org/p/chromium/issues/detail?id=688906 for Blink issue.
53 // See https://bugzilla.mozilla.org/show_bug.cgi?id=1387483 for Firefox issue.
54 // See https://github.com/web-platform-tests/wpt/issues/7693 for WHATWG tests issue.
55 // See https://developer.mozilla.org/en-US/docs/Web/API/Streams_API for more details on the Streams API
56 // and browser support.
57 body, err := ioutil.ReadAll(req.Body)
59 req.Body.Close() // RoundTrip must always close the body, including on errors.
65 respPromise := js.Global().Call("fetch", req.URL.String(), opt)
67 respCh = make(chan *Response, 1)
68 errCh = make(chan error, 1)
70 success := js.NewCallback(func(args []js.Value) {
73 // https://developer.mozilla.org/en-US/docs/Web/API/Headers/entries
74 headersIt := result.Get("headers").Call("entries")
76 n := headersIt.Call("next")
77 if n.Get("done").Bool() {
80 pair := n.Get("value")
81 key, value := pair.Index(0).String(), pair.Index(1).String()
82 ck := CanonicalHeaderKey(key)
83 header[ck] = append(header[ck], value)
86 contentLength := int64(0)
87 if cl, err := strconv.ParseInt(header.Get("Content-Length"), 10, 64); err == nil {
91 b := result.Get("body")
92 var body io.ReadCloser
93 if b != js.Undefined() {
94 body = &streamReader{stream: b.Call("getReader")}
96 // Fall back to using ArrayBuffer
97 // https://developer.mozilla.org/en-US/docs/Web/API/Body/arrayBuffer
98 body = &arrayReader{arrayPromise: result.Call("arrayBuffer")}
102 case respCh <- &Response{
103 Status: result.Get("status").String() + " " + StatusText(result.Get("status").Int()),
104 StatusCode: result.Get("status").Int(),
106 ContentLength: contentLength,
110 case <-req.Context().Done():
113 defer success.Release()
114 failure := js.NewCallback(func(args []js.Value) {
115 err := fmt.Errorf("net/http: fetch() failed: %s", args[0].String())
118 case <-req.Context().Done():
121 defer failure.Release()
122 respPromise.Call("then", success, failure)
124 case <-req.Context().Done():
125 if ac != js.Undefined() {
126 // Abort the Fetch request
129 return nil, req.Context().Err()
130 case resp := <-respCh:
137 var errClosed = errors.New("net/http: reader is closed")
139 // useFakeNetwork is used to determine whether the request is made
140 // by a test and should be made to use the fake in-memory network.
141 func useFakeNetwork() bool {
142 return len(os.Args) > 0 && strings.HasSuffix(os.Args[0], ".test")
145 // streamReader implements an io.ReadCloser wrapper for ReadableStream.
146 // See https://fetch.spec.whatwg.org/#readablestream for more information.
147 type streamReader struct {
150 err error // sticky read error
153 func (r *streamReader) Read(p []byte) (n int, err error) {
157 if len(r.pending) == 0 {
159 bCh = make(chan []byte, 1)
160 errCh = make(chan error, 1)
162 success := js.NewCallback(func(args []js.Value) {
164 if result.Get("done").Bool() {
168 value := make([]byte, result.Get("value").Get("byteLength").Int())
169 a := js.TypedArrayOf(value)
170 a.Call("set", result.Get("value"))
174 defer success.Release()
175 failure := js.NewCallback(func(args []js.Value) {
176 // Assumes it's a TypeError. See
177 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError
178 // for more information on this type. See
179 // https://streams.spec.whatwg.org/#byob-reader-read for the spec on
181 errCh <- errors.New(args[0].Get("message").String())
183 defer failure.Release()
184 r.stream.Call("read").Call("then", success, failure)
193 n = copy(p, r.pending)
194 r.pending = r.pending[n:]
198 func (r *streamReader) Close() error {
199 // This ignores any error returned from cancel method. So far, I did not encounter any concrete
200 // situation where reporting the error is meaningful. Most users ignore error from resp.Body.Close().
201 // If there's a need to report error here, it can be implemented and tested when that need comes up.
202 r.stream.Call("cancel")
209 // arrayReader implements an io.ReadCloser wrapper for ArrayBuffer.
210 // https://developer.mozilla.org/en-US/docs/Web/API/Body/arrayBuffer.
211 type arrayReader struct {
212 arrayPromise js.Value
215 err error // sticky read error
218 func (r *arrayReader) Read(p []byte) (n int, err error) {
225 bCh = make(chan []byte, 1)
226 errCh = make(chan error, 1)
228 success := js.NewCallback(func(args []js.Value) {
229 // Wrap the input ArrayBuffer with a Uint8Array
230 uint8arrayWrapper := js.Global().Get("Uint8Array").New(args[0])
231 value := make([]byte, uint8arrayWrapper.Get("byteLength").Int())
232 a := js.TypedArrayOf(value)
233 a.Call("set", uint8arrayWrapper)
237 defer success.Release()
238 failure := js.NewCallback(func(args []js.Value) {
239 // Assumes it's a TypeError. See
240 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError
241 // for more information on this type.
242 // See https://fetch.spec.whatwg.org/#concept-body-consume-body for reasons this might error.
243 errCh <- errors.New(args[0].Get("message").String())
245 defer failure.Release()
246 r.arrayPromise.Call("then", success, failure)
254 if len(r.pending) == 0 {
257 n = copy(p, r.pending)
258 r.pending = r.pending[n:]
262 func (r *arrayReader) Close() error {