Skip to content

Commit 6df6467

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 6df6467

File tree

4 files changed

+285
-5
lines changed

4 files changed

+285
-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: 267 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,267 @@
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+
host, _, err := net.SplitHostPort(req.Host)
140+
if err != nil {
141+
host = req.Host
142+
}
143+
if ip := net.ParseIP(host); ip != nil {
144+
return ip.IsLoopback(ip)
145+
}
146+
return host == "localhost"
147+
}
148+
149+
// streamReader implements an io.ReadCloser wrapper for ReadableStream.
150+
// See https://fetch.spec.whatwg.org/#readablestream for more information.
151+
type streamReader struct {
152+
pending []byte
153+
stream js.Value
154+
err error // sticky read error
155+
}
156+
157+
func (r *streamReader) Read(p []byte) (n int, err error) {
158+
if r.err != nil {
159+
return 0, r.err
160+
}
161+
if len(r.pending) == 0 {
162+
var (
163+
bCh = make(chan []byte, 1)
164+
errCh = make(chan error, 1)
165+
)
166+
success := js.NewCallback(func(args []js.Value) {
167+
result := args[0]
168+
if result.Get("done").Bool() {
169+
errCh <- io.EOF
170+
return
171+
}
172+
value := make([]byte, result.Get("value").Get("byteLength").Int())
173+
js.ValueOf(value).Call("set", result.Get("value"))
174+
bCh <- value
175+
})
176+
defer success.Close()
177+
failure := js.NewCallback(func(args []js.Value) {
178+
// Assumes it's a TypeError. See
179+
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError
180+
// for more information on this type. See
181+
// https://streams.spec.whatwg.org/#byob-reader-read for the spec on
182+
// the read method.
183+
errCh <- errors.New(args[0].Get("message").String())
184+
})
185+
defer failure.Close()
186+
r.stream.Call("read").Call("then", success, failure)
187+
select {
188+
case b := <-bCh:
189+
r.pending = b
190+
case err := <-errCh:
191+
r.err = err
192+
return 0, err
193+
}
194+
}
195+
n = copy(p, r.pending)
196+
r.pending = r.pending[n:]
197+
return n, nil
198+
}
199+
200+
func (r *streamReader) Close() error {
201+
// This ignores any error returned from cancel method. So far, I did not encounter any concrete
202+
// situation where reporting the error is meaningful. Most users ignore error from resp.Body.Close().
203+
// If there's a need to report error here, it can be implemented and tested when that need comes up.
204+
r.stream.Call("cancel")
205+
if r.err == nil {
206+
r.err = errClosed
207+
}
208+
return nil
209+
}
210+
211+
// arrayReader implements an io.ReadCloser wrapper for ArrayBuffer.
212+
// https://developer.mozilla.org/en-US/docs/Web/API/Body/arrayBuffer.
213+
type arrayReader struct {
214+
arrayPromise js.Value
215+
pending []byte
216+
read bool
217+
err error // sticky read error
218+
}
219+
220+
func (r *arrayReader) Read(p []byte) (n int, err error) {
221+
if r.err != nil {
222+
return 0, r.err
223+
}
224+
if !r.read {
225+
r.read = true
226+
var (
227+
bCh = make(chan []byte, 1)
228+
errCh = make(chan error, 1)
229+
)
230+
success := js.NewCallback(func(args []js.Value) {
231+
// Wrap the input ArrayBuffer with a Uint8Array
232+
uint8arrayWrapper := js.Global.Get("Uint8Array").New(args[0])
233+
value := make([]byte, uint8arrayWrapper.Get("byteLength").Int())
234+
js.ValueOf(value).Call("set", uint8arrayWrapper)
235+
bCh <- value
236+
})
237+
defer success.Close()
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())
244+
})
245+
defer failure.Close()
246+
r.arrayPromise.Call("then", success, failure)
247+
select {
248+
case b := <-bCh:
249+
r.pending = b
250+
case err := <-errCh:
251+
return 0, err
252+
}
253+
}
254+
if len(r.pending) == 0 {
255+
return 0, io.EOF
256+
}
257+
n = copy(p, r.pending)
258+
r.pending = r.pending[n:]
259+
return n, nil
260+
}
261+
262+
func (r *arrayReader) Close() error {
263+
if r.err == nil {
264+
r.err = errClosed
265+
}
266+
return nil
267+
}

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)