Skip to content

Commit a710973

Browse files
net/http: add js/wasm compatible DefaultTransport
Adds a new Transport type for the js/wasm target that uses the JavaScript Fetch API for sending HTTP requests. Support for streaming response bodies is used when available, falling back to reading the entire response into memory at once.
1 parent 65c365b commit a710973

File tree

4 files changed

+281
-5
lines changed

4 files changed

+281
-5
lines changed

src/go/build/deps_test.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -410,6 +410,7 @@ var pkgDeps = map[string][]string{
410410
"net/http/httptrace",
411411
"net/http/internal",
412412
"runtime/debug",
413+
"syscall/js",
413414
},
414415
"net/http/internal": {"L4"},
415416
"net/http/httptrace": {"context", "crypto/tls", "internal/nettrace", "net", "reflect", "time"},

src/net/http/roundtrip.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
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+
// RoundTrip implements the RoundTripper interface.
10+
//
11+
// For higher-level HTTP client support (such as handling of cookies
12+
// and redirects), see Get, Post, and the Client type.
13+
func (t *Transport) RoundTrip(req *Request) (*Response, error) {
14+
return t.roundTrip(req)
15+
}

src/net/http/roundtrip_js.go

Lines changed: 263 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,263 @@
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+
"io/ioutil"
14+
"net"
15+
"strconv"
16+
"syscall/js"
17+
)
18+
19+
// RoundTrip implements the RoundTripper interface using the WHATWG Fetch API.
20+
func (*Transport) RoundTrip(req *Request) (*Response, error) {
21+
if useFakeNetwork(req) {
22+
return t.roundTrip(req)
23+
}
24+
headers := js.Global.Get("Headers").New()
25+
for key, values := range req.Header {
26+
for _, value := range values {
27+
headers.Call("append", key, value)
28+
}
29+
}
30+
31+
ac := js.Global.Get("AbortController")
32+
if ac != js.Undefined {
33+
// Some browsers that support WASM don't necessarily support
34+
// the AbortController. See
35+
// https://developer.mozilla.org/en-US/docs/Web/API/AbortController#Browser_compatibility.
36+
ac = ac.New()
37+
}
38+
39+
opt := js.Global.Get("Object").New()
40+
// See https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch
41+
// for options available.
42+
opt.Set("headers", headers)
43+
opt.Set("method", req.Method)
44+
opt.Set("credentials", "same-origin")
45+
if ac != js.Undefined {
46+
opt.Set("signal", ac.Get("signal"))
47+
}
48+
49+
if req.Body != nil {
50+
// TODO(johanbrandhorst): Stream request body when possible.
51+
// See https://bugs.chromium.org/p/chromium/issues/detail?id=688906 for Blink issue.
52+
// See https://bugzilla.mozilla.org/show_bug.cgi?id=1387483 for Firefox issue.
53+
// See https://github.com/web-platform-tests/wpt/issues/7693 for WHATWG tests issue.
54+
// See https://developer.mozilla.org/en-US/docs/Web/API/Streams_API for more details on the Streams API
55+
// and browser support.
56+
body, err := ioutil.ReadAll(req.Body)
57+
if err != nil {
58+
req.Body.Close() // RoundTrip must always close the body, including on errors.
59+
return nil, err
60+
}
61+
req.Body.Close()
62+
opt.Set("body", body)
63+
}
64+
respPromise := js.Global.Call("fetch", req.URL.String(), opt)
65+
var (
66+
respCh = make(chan *Response, 1)
67+
errCh = make(chan error, 1)
68+
)
69+
success := js.NewCallback(func(args []js.Value) {
70+
result := args[0]
71+
header := Header{}
72+
// https://developer.mozilla.org/en-US/docs/Web/API/Headers/entries
73+
headersIt := result.Get("headers").Call("entries")
74+
for {
75+
n := headersIt.Call("next")
76+
if n.Get("done").Bool() {
77+
break
78+
}
79+
pair := n.Get("value")
80+
key, value := pair.Index(0).String(), pair.Index(1).String()
81+
ck := CanonicalHeaderKey(key)
82+
header[ck] = append(header[ck], value)
83+
}
84+
85+
contentLength := int64(0)
86+
if cl, err := strconv.ParseInt(header.Get("Content-Length"), 10, 64); err == nil {
87+
contentLength = cl
88+
}
89+
90+
b := result.Get("body")
91+
var body io.ReadCloser
92+
if b != js.Undefined {
93+
body = &streamReader{stream: b.Call("getReader")}
94+
} else {
95+
// Fall back to using ArrayBuffer
96+
// https://developer.mozilla.org/en-US/docs/Web/API/Body/arrayBuffer
97+
body = &arrayReader{arrayPromise: result.Call("arrayBuffer")}
98+
}
99+
100+
select {
101+
case respCh <- &Response{
102+
Status: result.Get("status").String() + " " + StatusText(result.Get("status").Int()),
103+
StatusCode: result.Get("status").Int(),
104+
Header: header,
105+
ContentLength: contentLength,
106+
Body: body,
107+
Request: req,
108+
}:
109+
case <-req.Context().Done():
110+
}
111+
})
112+
defer success.Close()
113+
failure := js.NewCallback(func(args []js.Value) {
114+
err := fmt.Errorf("net/http: fetch() failed: %s", args[0].String())
115+
select {
116+
case errCh <- err:
117+
case <-req.Context().Done():
118+
}
119+
})
120+
defer failure.Close()
121+
respPromise.Call("then", success, failure)
122+
select {
123+
case <-req.Context().Done():
124+
if ac != js.Undefined {
125+
// Abort the Fetch request
126+
ac.Call("abort")
127+
}
128+
return nil, req.Context().Err()
129+
case resp := <-respCh:
130+
return resp, nil
131+
case err := <-errCh:
132+
return nil, err
133+
}
134+
}
135+
136+
// useFakeNetwork is used to determine whether the request is made
137+
// by a test and should be made to use the fake in-memory network.
138+
func useFakeNetwork(req *Request) bool {
139+
if ip := net.ParseIP(req.Host); ip != nil {
140+
return ip.IsLoopback(ip)
141+
}
142+
return req.Host == "localhost"
143+
}
144+
145+
// streamReader implements an io.ReadCloser wrapper for ReadableStream.
146+
// See https://fetch.spec.whatwg.org/#readablestream for more information.
147+
type streamReader struct {
148+
pending []byte
149+
stream js.Value
150+
err error // sticky read error
151+
}
152+
153+
func (r *streamReader) Read(p []byte) (n int, err error) {
154+
if r.err != nil {
155+
return 0, r.err
156+
}
157+
if len(r.pending) == 0 {
158+
var (
159+
bCh = make(chan []byte, 1)
160+
errCh = make(chan error, 1)
161+
)
162+
success := js.NewCallback(func(args []js.Value) {
163+
result := args[0]
164+
if result.Get("done").Bool() {
165+
errCh <- io.EOF
166+
return
167+
}
168+
value := make([]byte, result.Get("value").Get("byteLength").Int())
169+
js.ValueOf(value).Call("set", result.Get("value"))
170+
bCh <- value
171+
})
172+
defer success.Close()
173+
failure := js.NewCallback(func(args []js.Value) {
174+
// Assumes it's a TypeError. See
175+
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError
176+
// for more information on this type. See
177+
// https://streams.spec.whatwg.org/#byob-reader-read for the spec on
178+
// the read method.
179+
errCh <- errors.New(args[0].Get("message").String())
180+
})
181+
defer failure.Close()
182+
r.stream.Call("read").Call("then", success, failure)
183+
select {
184+
case b := <-bCh:
185+
r.pending = b
186+
case err := <-errCh:
187+
r.err = err
188+
return 0, err
189+
}
190+
}
191+
n = copy(p, r.pending)
192+
r.pending = r.pending[n:]
193+
return n, nil
194+
}
195+
196+
func (r *streamReader) Close() error {
197+
// This ignores any error returned from cancel method. So far, I did not encounter any concrete
198+
// situation where reporting the error is meaningful. Most users ignore error from resp.Body.Close().
199+
// If there's a need to report error here, it can be implemented and tested when that need comes up.
200+
r.stream.Call("cancel")
201+
if r.err == nil {
202+
r.err = errClosed
203+
}
204+
return nil
205+
}
206+
207+
// arrayReader implements an io.ReadCloser wrapper for ArrayBuffer.
208+
// https://developer.mozilla.org/en-US/docs/Web/API/Body/arrayBuffer.
209+
type arrayReader struct {
210+
arrayPromise js.Value
211+
pending []byte
212+
read bool
213+
err error // sticky read error
214+
}
215+
216+
func (r *arrayReader) Read(p []byte) (n int, err error) {
217+
if r.err != nil {
218+
return 0, r.err
219+
}
220+
if !r.read {
221+
r.read = true
222+
var (
223+
bCh = make(chan []byte, 1)
224+
errCh = make(chan error, 1)
225+
)
226+
success := js.NewCallback(func(args []js.Value) {
227+
// Wrap the input ArrayBuffer with a Uint8Array
228+
uint8arrayWrapper := js.Global.Get("Uint8Array").New(args[0])
229+
value := make([]byte, uint8arrayWrapper.Get("byteLength").Int())
230+
js.ValueOf(value).Call("set", uint8arrayWrapper)
231+
bCh <- value
232+
})
233+
defer success.Close()
234+
failure := js.NewCallback(func(args []js.Value) {
235+
// Assumes it's a TypeError. See
236+
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError
237+
// for more information on this type.
238+
// See https://fetch.spec.whatwg.org/#concept-body-consume-body for reasons this might error.
239+
errCh <- errors.New(args[0].Get("message").String())
240+
})
241+
defer failure.Close()
242+
r.arrayPromise.Call("then", success, failure)
243+
select {
244+
case b := <-bCh:
245+
r.pending = b
246+
case err := <-errCh:
247+
return 0, err
248+
}
249+
}
250+
if len(r.pending) == 0 {
251+
return 0, io.EOF
252+
}
253+
n = copy(p, r.pending)
254+
r.pending = r.pending[n:]
255+
return n, nil
256+
}
257+
258+
func (r *arrayReader) Close() error {
259+
if r.err == nil {
260+
r.err = errClosed
261+
}
262+
return nil
263+
}

src/net/http/transport.go

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -342,11 +342,8 @@ func (tr *transportRequest) setError(err error) {
342342
tr.mu.Unlock()
343343
}
344344

345-
// RoundTrip implements the RoundTripper interface.
346-
//
347-
// For higher-level HTTP client support (such as handling of cookies
348-
// and redirects), see Get, Post, and the Client type.
349-
func (t *Transport) RoundTrip(req *Request) (*Response, error) {
345+
// roundTrip implements a RoundTripper over HTTP.
346+
func (t *Transport) roundTrip(req *Request) (*Response, error) {
350347
t.nextProtoOnce.Do(t.onceSetNextProtoDefaults)
351348
ctx := req.Context()
352349
trace := httptrace.ContextClientTrace(ctx)

0 commit comments

Comments
 (0)