Skip to content

Commit 7c13eba

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 7c13eba

File tree

3 files changed

+377
-128
lines changed

3 files changed

+377
-128
lines changed

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

0 commit comments

Comments
 (0)