Skip to content

Commit c068b7f

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 c068b7f

File tree

4 files changed

+273
-5
lines changed

4 files changed

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

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)