Skip to content

Commit 49b5acc

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 49b5acc

File tree

4 files changed

+279
-5
lines changed

4 files changed

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

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)