Skip to content

Commit a3dde72

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 a3dde72

File tree

4 files changed

+267
-5
lines changed

4 files changed

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

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)