]> Cypherpunks.ru repositories - gostls13.git/blob - src/net/http/roundtrip_js.go
all: update references to symbols moved from io/ioutil to io
[gostls13.git] / src / net / http / roundtrip_js.go
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.
4
5 // +build js,wasm
6
7 package http
8
9 import (
10         "errors"
11         "fmt"
12         "io"
13         "strconv"
14         "syscall/js"
15 )
16
17 var uint8Array = js.Global().Get("Uint8Array")
18
19 // jsFetchMode is a Request.Header map key that, if present,
20 // signals that the map entry is actually an option to the Fetch API mode setting.
21 // Valid values are: "cors", "no-cors", "same-origin", "navigate"
22 // The default is "same-origin".
23 //
24 // Reference: https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters
25 const jsFetchMode = "js.fetch:mode"
26
27 // jsFetchCreds is a Request.Header map key that, if present,
28 // signals that the map entry is actually an option to the Fetch API credentials setting.
29 // Valid values are: "omit", "same-origin", "include"
30 // The default is "same-origin".
31 //
32 // Reference: https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters
33 const jsFetchCreds = "js.fetch:credentials"
34
35 // jsFetchRedirect is a Request.Header map key that, if present,
36 // signals that the map entry is actually an option to the Fetch API redirect setting.
37 // Valid values are: "follow", "error", "manual"
38 // The default is "follow".
39 //
40 // Reference: https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters
41 const jsFetchRedirect = "js.fetch:redirect"
42
43 var useFakeNetwork = js.Global().Get("fetch").IsUndefined()
44
45 // RoundTrip implements the RoundTripper interface using the WHATWG Fetch API.
46 func (t *Transport) RoundTrip(req *Request) (*Response, error) {
47         if useFakeNetwork {
48                 return t.roundTrip(req)
49         }
50
51         ac := js.Global().Get("AbortController")
52         if !ac.IsUndefined() {
53                 // Some browsers that support WASM don't necessarily support
54                 // the AbortController. See
55                 // https://developer.mozilla.org/en-US/docs/Web/API/AbortController#Browser_compatibility.
56                 ac = ac.New()
57         }
58
59         opt := js.Global().Get("Object").New()
60         // See https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch
61         // for options available.
62         opt.Set("method", req.Method)
63         opt.Set("credentials", "same-origin")
64         if h := req.Header.Get(jsFetchCreds); h != "" {
65                 opt.Set("credentials", h)
66                 req.Header.Del(jsFetchCreds)
67         }
68         if h := req.Header.Get(jsFetchMode); h != "" {
69                 opt.Set("mode", h)
70                 req.Header.Del(jsFetchMode)
71         }
72         if h := req.Header.Get(jsFetchRedirect); h != "" {
73                 opt.Set("redirect", h)
74                 req.Header.Del(jsFetchRedirect)
75         }
76         if !ac.IsUndefined() {
77                 opt.Set("signal", ac.Get("signal"))
78         }
79         headers := js.Global().Get("Headers").New()
80         for key, values := range req.Header {
81                 for _, value := range values {
82                         headers.Call("append", key, value)
83                 }
84         }
85         opt.Set("headers", headers)
86
87         if req.Body != nil {
88                 // TODO(johanbrandhorst): Stream request body when possible.
89                 // See https://bugs.chromium.org/p/chromium/issues/detail?id=688906 for Blink issue.
90                 // See https://bugzilla.mozilla.org/show_bug.cgi?id=1387483 for Firefox issue.
91                 // See https://github.com/web-platform-tests/wpt/issues/7693 for WHATWG tests issue.
92                 // See https://developer.mozilla.org/en-US/docs/Web/API/Streams_API for more details on the Streams API
93                 // and browser support.
94                 body, err := io.ReadAll(req.Body)
95                 if err != nil {
96                         req.Body.Close() // RoundTrip must always close the body, including on errors.
97                         return nil, err
98                 }
99                 req.Body.Close()
100                 if len(body) != 0 {
101                         buf := uint8Array.New(len(body))
102                         js.CopyBytesToJS(buf, body)
103                         opt.Set("body", buf)
104                 }
105         }
106
107         fetchPromise := js.Global().Call("fetch", req.URL.String(), opt)
108         var (
109                 respCh           = make(chan *Response, 1)
110                 errCh            = make(chan error, 1)
111                 success, failure js.Func
112         )
113         success = js.FuncOf(func(this js.Value, args []js.Value) interface{} {
114                 success.Release()
115                 failure.Release()
116
117                 result := args[0]
118                 header := Header{}
119                 // https://developer.mozilla.org/en-US/docs/Web/API/Headers/entries
120                 headersIt := result.Get("headers").Call("entries")
121                 for {
122                         n := headersIt.Call("next")
123                         if n.Get("done").Bool() {
124                                 break
125                         }
126                         pair := n.Get("value")
127                         key, value := pair.Index(0).String(), pair.Index(1).String()
128                         ck := CanonicalHeaderKey(key)
129                         header[ck] = append(header[ck], value)
130                 }
131
132                 contentLength := int64(0)
133                 if cl, err := strconv.ParseInt(header.Get("Content-Length"), 10, 64); err == nil {
134                         contentLength = cl
135                 }
136
137                 b := result.Get("body")
138                 var body io.ReadCloser
139                 // The body is undefined when the browser does not support streaming response bodies (Firefox),
140                 // and null in certain error cases, i.e. when the request is blocked because of CORS settings.
141                 if !b.IsUndefined() && !b.IsNull() {
142                         body = &streamReader{stream: b.Call("getReader")}
143                 } else {
144                         // Fall back to using ArrayBuffer
145                         // https://developer.mozilla.org/en-US/docs/Web/API/Body/arrayBuffer
146                         body = &arrayReader{arrayPromise: result.Call("arrayBuffer")}
147                 }
148
149                 code := result.Get("status").Int()
150                 respCh <- &Response{
151                         Status:        fmt.Sprintf("%d %s", code, StatusText(code)),
152                         StatusCode:    code,
153                         Header:        header,
154                         ContentLength: contentLength,
155                         Body:          body,
156                         Request:       req,
157                 }
158
159                 return nil
160         })
161         failure = js.FuncOf(func(this js.Value, args []js.Value) interface{} {
162                 success.Release()
163                 failure.Release()
164                 errCh <- fmt.Errorf("net/http: fetch() failed: %s", args[0].Get("message").String())
165                 return nil
166         })
167
168         fetchPromise.Call("then", success, failure)
169         select {
170         case <-req.Context().Done():
171                 if !ac.IsUndefined() {
172                         // Abort the Fetch request.
173                         ac.Call("abort")
174                 }
175                 return nil, req.Context().Err()
176         case resp := <-respCh:
177                 return resp, nil
178         case err := <-errCh:
179                 return nil, err
180         }
181 }
182
183 var errClosed = errors.New("net/http: reader is closed")
184
185 // streamReader implements an io.ReadCloser wrapper for ReadableStream.
186 // See https://fetch.spec.whatwg.org/#readablestream for more information.
187 type streamReader struct {
188         pending []byte
189         stream  js.Value
190         err     error // sticky read error
191 }
192
193 func (r *streamReader) Read(p []byte) (n int, err error) {
194         if r.err != nil {
195                 return 0, r.err
196         }
197         if len(r.pending) == 0 {
198                 var (
199                         bCh   = make(chan []byte, 1)
200                         errCh = make(chan error, 1)
201                 )
202                 success := js.FuncOf(func(this js.Value, args []js.Value) interface{} {
203                         result := args[0]
204                         if result.Get("done").Bool() {
205                                 errCh <- io.EOF
206                                 return nil
207                         }
208                         value := make([]byte, result.Get("value").Get("byteLength").Int())
209                         js.CopyBytesToGo(value, result.Get("value"))
210                         bCh <- value
211                         return nil
212                 })
213                 defer success.Release()
214                 failure := js.FuncOf(func(this js.Value, args []js.Value) interface{} {
215                         // Assumes it's a TypeError. See
216                         // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError
217                         // for more information on this type. See
218                         // https://streams.spec.whatwg.org/#byob-reader-read for the spec on
219                         // the read method.
220                         errCh <- errors.New(args[0].Get("message").String())
221                         return nil
222                 })
223                 defer failure.Release()
224                 r.stream.Call("read").Call("then", success, failure)
225                 select {
226                 case b := <-bCh:
227                         r.pending = b
228                 case err := <-errCh:
229                         r.err = err
230                         return 0, err
231                 }
232         }
233         n = copy(p, r.pending)
234         r.pending = r.pending[n:]
235         return n, nil
236 }
237
238 func (r *streamReader) Close() error {
239         // This ignores any error returned from cancel method. So far, I did not encounter any concrete
240         // situation where reporting the error is meaningful. Most users ignore error from resp.Body.Close().
241         // If there's a need to report error here, it can be implemented and tested when that need comes up.
242         r.stream.Call("cancel")
243         if r.err == nil {
244                 r.err = errClosed
245         }
246         return nil
247 }
248
249 // arrayReader implements an io.ReadCloser wrapper for ArrayBuffer.
250 // https://developer.mozilla.org/en-US/docs/Web/API/Body/arrayBuffer.
251 type arrayReader struct {
252         arrayPromise js.Value
253         pending      []byte
254         read         bool
255         err          error // sticky read error
256 }
257
258 func (r *arrayReader) Read(p []byte) (n int, err error) {
259         if r.err != nil {
260                 return 0, r.err
261         }
262         if !r.read {
263                 r.read = true
264                 var (
265                         bCh   = make(chan []byte, 1)
266                         errCh = make(chan error, 1)
267                 )
268                 success := js.FuncOf(func(this js.Value, args []js.Value) interface{} {
269                         // Wrap the input ArrayBuffer with a Uint8Array
270                         uint8arrayWrapper := uint8Array.New(args[0])
271                         value := make([]byte, uint8arrayWrapper.Get("byteLength").Int())
272                         js.CopyBytesToGo(value, uint8arrayWrapper)
273                         bCh <- value
274                         return nil
275                 })
276                 defer success.Release()
277                 failure := js.FuncOf(func(this js.Value, args []js.Value) interface{} {
278                         // Assumes it's a TypeError. See
279                         // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError
280                         // for more information on this type.
281                         // See https://fetch.spec.whatwg.org/#concept-body-consume-body for reasons this might error.
282                         errCh <- errors.New(args[0].Get("message").String())
283                         return nil
284                 })
285                 defer failure.Release()
286                 r.arrayPromise.Call("then", success, failure)
287                 select {
288                 case b := <-bCh:
289                         r.pending = b
290                 case err := <-errCh:
291                         return 0, err
292                 }
293         }
294         if len(r.pending) == 0 {
295                 return 0, io.EOF
296         }
297         n = copy(p, r.pending)
298         r.pending = r.pending[n:]
299         return n, nil
300 }
301
302 func (r *arrayReader) Close() error {
303         if r.err == nil {
304                 r.err = errClosed
305         }
306         return nil
307 }