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 var useFakeNetwork = js.Global().Get("fetch").IsUndefined()
46 // RoundTrip implements the RoundTripper interface using the WHATWG Fetch API.
47 func (t *Transport) RoundTrip(req *Request) (*Response, error) {
49 return t.roundTrip(req)
52 ac := js.Global().Get("AbortController")
53 if !ac.IsUndefined() {
54 // Some browsers that support WASM don't necessarily support
55 // the AbortController. See
56 // https://developer.mozilla.org/en-US/docs/Web/API/AbortController#Browser_compatibility.
60 opt := js.Global().Get("Object").New()
61 // See https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch
62 // for options available.
63 opt.Set("method", req.Method)
64 opt.Set("credentials", "same-origin")
65 if h := req.Header.Get(jsFetchCreds); h != "" {
66 opt.Set("credentials", h)
67 req.Header.Del(jsFetchCreds)
69 if h := req.Header.Get(jsFetchMode); h != "" {
71 req.Header.Del(jsFetchMode)
73 if h := req.Header.Get(jsFetchRedirect); h != "" {
74 opt.Set("redirect", h)
75 req.Header.Del(jsFetchRedirect)
77 if !ac.IsUndefined() {
78 opt.Set("signal", ac.Get("signal"))
80 headers := js.Global().Get("Headers").New()
81 for key, values := range req.Header {
82 for _, value := range values {
83 headers.Call("append", key, value)
86 opt.Set("headers", headers)
89 // TODO(johanbrandhorst): Stream request body when possible.
90 // See https://bugs.chromium.org/p/chromium/issues/detail?id=688906 for Blink issue.
91 // See https://bugzilla.mozilla.org/show_bug.cgi?id=1387483 for Firefox issue.
92 // See https://github.com/web-platform-tests/wpt/issues/7693 for WHATWG tests issue.
93 // See https://developer.mozilla.org/en-US/docs/Web/API/Streams_API for more details on the Streams API
94 // and browser support.
95 body, err := ioutil.ReadAll(req.Body)
97 req.Body.Close() // RoundTrip must always close the body, including on errors.
101 buf := uint8Array.New(len(body))
102 js.CopyBytesToJS(buf, body)
106 fetchPromise := js.Global().Call("fetch", req.URL.String(), opt)
108 respCh = make(chan *Response, 1)
109 errCh = make(chan error, 1)
110 success, failure js.Func
112 success = js.FuncOf(func(this js.Value, args []js.Value) interface{} {
118 // https://developer.mozilla.org/en-US/docs/Web/API/Headers/entries
119 headersIt := result.Get("headers").Call("entries")
121 n := headersIt.Call("next")
122 if n.Get("done").Bool() {
125 pair := n.Get("value")
126 key, value := pair.Index(0).String(), pair.Index(1).String()
127 ck := CanonicalHeaderKey(key)
128 header[ck] = append(header[ck], value)
131 contentLength := int64(0)
132 if cl, err := strconv.ParseInt(header.Get("Content-Length"), 10, 64); err == nil {
136 b := result.Get("body")
137 var body io.ReadCloser
138 // The body is undefined when the browser does not support streaming response bodies (Firefox),
139 // and null in certain error cases, i.e. when the request is blocked because of CORS settings.
140 if !b.IsUndefined() && !b.IsNull() {
141 body = &streamReader{stream: b.Call("getReader")}
143 // Fall back to using ArrayBuffer
144 // https://developer.mozilla.org/en-US/docs/Web/API/Body/arrayBuffer
145 body = &arrayReader{arrayPromise: result.Call("arrayBuffer")}
148 code := result.Get("status").Int()
150 Status: fmt.Sprintf("%d %s", code, StatusText(code)),
153 ContentLength: contentLength,
160 failure = js.FuncOf(func(this js.Value, args []js.Value) interface{} {
163 errCh <- fmt.Errorf("net/http: fetch() failed: %s", args[0].Get("message").String())
167 fetchPromise.Call("then", success, failure)
169 case <-req.Context().Done():
170 if !ac.IsUndefined() {
171 // Abort the Fetch request.
174 return nil, req.Context().Err()
175 case resp := <-respCh:
182 var errClosed = errors.New("net/http: reader is closed")
184 // streamReader implements an io.ReadCloser wrapper for ReadableStream.
185 // See https://fetch.spec.whatwg.org/#readablestream for more information.
186 type streamReader struct {
189 err error // sticky read error
192 func (r *streamReader) Read(p []byte) (n int, err error) {
196 if len(r.pending) == 0 {
198 bCh = make(chan []byte, 1)
199 errCh = make(chan error, 1)
201 success := js.FuncOf(func(this js.Value, args []js.Value) interface{} {
203 if result.Get("done").Bool() {
207 value := make([]byte, result.Get("value").Get("byteLength").Int())
208 js.CopyBytesToGo(value, result.Get("value"))
212 defer success.Release()
213 failure := js.FuncOf(func(this js.Value, args []js.Value) interface{} {
214 // Assumes it's a TypeError. See
215 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError
216 // for more information on this type. See
217 // https://streams.spec.whatwg.org/#byob-reader-read for the spec on
219 errCh <- errors.New(args[0].Get("message").String())
222 defer failure.Release()
223 r.stream.Call("read").Call("then", success, failure)
232 n = copy(p, r.pending)
233 r.pending = r.pending[n:]
237 func (r *streamReader) Close() error {
238 // This ignores any error returned from cancel method. So far, I did not encounter any concrete
239 // situation where reporting the error is meaningful. Most users ignore error from resp.Body.Close().
240 // If there's a need to report error here, it can be implemented and tested when that need comes up.
241 r.stream.Call("cancel")
248 // arrayReader implements an io.ReadCloser wrapper for ArrayBuffer.
249 // https://developer.mozilla.org/en-US/docs/Web/API/Body/arrayBuffer.
250 type arrayReader struct {
251 arrayPromise js.Value
254 err error // sticky read error
257 func (r *arrayReader) Read(p []byte) (n int, err error) {
264 bCh = make(chan []byte, 1)
265 errCh = make(chan error, 1)
267 success := js.FuncOf(func(this js.Value, args []js.Value) interface{} {
268 // Wrap the input ArrayBuffer with a Uint8Array
269 uint8arrayWrapper := uint8Array.New(args[0])
270 value := make([]byte, uint8arrayWrapper.Get("byteLength").Int())
271 js.CopyBytesToGo(value, uint8arrayWrapper)
275 defer success.Release()
276 failure := js.FuncOf(func(this js.Value, args []js.Value) interface{} {
277 // Assumes it's a TypeError. See
278 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError
279 // for more information on this type.
280 // See https://fetch.spec.whatwg.org/#concept-body-consume-body for reasons this might error.
281 errCh <- errors.New(args[0].Get("message").String())
284 defer failure.Release()
285 r.arrayPromise.Call("then", success, failure)
293 if len(r.pending) == 0 {
296 n = copy(p, r.pending)
297 r.pending = r.pending[n:]
301 func (r *arrayReader) Close() error {