roundtrip_js.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  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. //go:build js && wasm
  5. package http
  6. import (
  7. "errors"
  8. "fmt"
  9. "io"
  10. "strconv"
  11. "syscall/js"
  12. )
  13. var uint8Array = js.Global().Get("Uint8Array")
  14. // jsFetchMode is a Request.Header map key that, if present,
  15. // signals that the map entry is actually an option to the Fetch API mode setting.
  16. // Valid values are: "cors", "no-cors", "same-origin", "navigate"
  17. // The default is "same-origin".
  18. //
  19. // Reference: https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters
  20. const jsFetchMode = "js.fetch:mode"
  21. // jsFetchCreds is a Request.Header map key that, if present,
  22. // signals that the map entry is actually an option to the Fetch API credentials setting.
  23. // Valid values are: "omit", "same-origin", "include"
  24. // The default is "same-origin".
  25. //
  26. // Reference: https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters
  27. const jsFetchCreds = "js.fetch:credentials"
  28. // jsFetchRedirect is a Request.Header map key that, if present,
  29. // signals that the map entry is actually an option to the Fetch API redirect setting.
  30. // Valid values are: "follow", "error", "manual"
  31. // The default is "follow".
  32. //
  33. // Reference: https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters
  34. const jsFetchRedirect = "js.fetch:redirect"
  35. // jsFetchMissing will be true if the Fetch API is not present in
  36. // the browser globals.
  37. var jsFetchMissing = js.Global().Get("fetch").IsUndefined()
  38. // RoundTrip implements the RoundTripper interface using the WHATWG Fetch API.
  39. func (t *Transport) RoundTrip(req *Request) (*Response, error) {
  40. // The Transport has a documented contract that states that if the DialContext or
  41. // DialTLSContext functions are set, they will be used to set up the connections.
  42. // If they aren't set then the documented contract is to use Dial or DialTLS, even
  43. // though they are deprecated. Therefore, if any of these are set, we should obey
  44. // the contract and dial using the regular round-trip instead. Otherwise, we'll try
  45. // to fall back on the Fetch API, unless it's not available.
  46. if t.Dial != nil || t.DialContext != nil || t.DialTLS != nil || t.DialTLSContext != nil || jsFetchMissing {
  47. return t.roundTrip(req)
  48. }
  49. ac := js.Global().Get("AbortController")
  50. if !ac.IsUndefined() {
  51. // Some browsers that support WASM don't necessarily support
  52. // the AbortController. See
  53. // https://developer.mozilla.org/en-US/docs/Web/API/AbortController#Browser_compatibility.
  54. ac = ac.New()
  55. }
  56. opt := js.Global().Get("Object").New()
  57. // See https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch
  58. // for options available.
  59. opt.Set("method", req.Method)
  60. opt.Set("credentials", "same-origin")
  61. if h := req.Header.Get(jsFetchCreds); h != "" {
  62. opt.Set("credentials", h)
  63. req.Header.Del(jsFetchCreds)
  64. }
  65. if h := req.Header.Get(jsFetchMode); h != "" {
  66. opt.Set("mode", h)
  67. req.Header.Del(jsFetchMode)
  68. }
  69. if h := req.Header.Get(jsFetchRedirect); h != "" {
  70. opt.Set("redirect", h)
  71. req.Header.Del(jsFetchRedirect)
  72. }
  73. if !ac.IsUndefined() {
  74. opt.Set("signal", ac.Get("signal"))
  75. }
  76. headers := js.Global().Get("Headers").New()
  77. for key, values := range req.Header {
  78. for _, value := range values {
  79. headers.Call("append", key, value)
  80. }
  81. }
  82. opt.Set("headers", headers)
  83. if req.Body != nil {
  84. // TODO(johanbrandhorst): Stream request body when possible.
  85. // See https://bugs.chromium.org/p/chromium/issues/detail?id=688906 for Blink issue.
  86. // See https://bugzilla.mozilla.org/show_bug.cgi?id=1387483 for Firefox issue.
  87. // See https://github.com/web-platform-tests/wpt/issues/7693 for WHATWG tests issue.
  88. // See https://developer.mozilla.org/en-US/docs/Web/API/Streams_API for more details on the Streams API
  89. // and browser support.
  90. body, err := io.ReadAll(req.Body)
  91. if err != nil {
  92. req.Body.Close() // RoundTrip must always close the body, including on errors.
  93. return nil, err
  94. }
  95. req.Body.Close()
  96. if len(body) != 0 {
  97. buf := uint8Array.New(len(body))
  98. js.CopyBytesToJS(buf, body)
  99. opt.Set("body", buf)
  100. }
  101. }
  102. fetchPromise := js.Global().Call("fetch", req.URL.String(), opt)
  103. var (
  104. respCh = make(chan *Response, 1)
  105. errCh = make(chan error, 1)
  106. success, failure js.Func
  107. )
  108. success = js.FuncOf(func(this js.Value, args []js.Value) any {
  109. success.Release()
  110. failure.Release()
  111. result := args[0]
  112. header := Header{}
  113. // https://developer.mozilla.org/en-US/docs/Web/API/Headers/entries
  114. headersIt := result.Get("headers").Call("entries")
  115. for {
  116. n := headersIt.Call("next")
  117. if n.Get("done").Bool() {
  118. break
  119. }
  120. pair := n.Get("value")
  121. key, value := pair.Index(0).String(), pair.Index(1).String()
  122. ck := CanonicalHeaderKey(key)
  123. header[ck] = append(header[ck], value)
  124. }
  125. contentLength := int64(0)
  126. clHeader := header.Get("Content-Length")
  127. switch {
  128. case clHeader != "":
  129. cl, err := strconv.ParseInt(clHeader, 10, 64)
  130. if err != nil {
  131. errCh <- fmt.Errorf("net/http: ill-formed Content-Length header: %v", err)
  132. return nil
  133. }
  134. if cl < 0 {
  135. // Content-Length values less than 0 are invalid.
  136. // See: https://datatracker.ietf.org/doc/html/rfc2616/#section-14.13
  137. errCh <- fmt.Errorf("net/http: invalid Content-Length header: %q", clHeader)
  138. return nil
  139. }
  140. contentLength = cl
  141. default:
  142. // If the response length is not declared, set it to -1.
  143. contentLength = -1
  144. }
  145. b := result.Get("body")
  146. var body io.ReadCloser
  147. // The body is undefined when the browser does not support streaming response bodies (Firefox),
  148. // and null in certain error cases, i.e. when the request is blocked because of CORS settings.
  149. if !b.IsUndefined() && !b.IsNull() {
  150. body = &streamReader{stream: b.Call("getReader")}
  151. } else {
  152. // Fall back to using ArrayBuffer
  153. // https://developer.mozilla.org/en-US/docs/Web/API/Body/arrayBuffer
  154. body = &arrayReader{arrayPromise: result.Call("arrayBuffer")}
  155. }
  156. code := result.Get("status").Int()
  157. respCh <- &Response{
  158. Status: fmt.Sprintf("%d %s", code, StatusText(code)),
  159. StatusCode: code,
  160. Header: header,
  161. ContentLength: contentLength,
  162. Body: body,
  163. Request: req,
  164. }
  165. return nil
  166. })
  167. failure = js.FuncOf(func(this js.Value, args []js.Value) any {
  168. success.Release()
  169. failure.Release()
  170. errCh <- fmt.Errorf("net/http: fetch() failed: %s", args[0].Get("message").String())
  171. return nil
  172. })
  173. fetchPromise.Call("then", success, failure)
  174. select {
  175. case <-req.Context().Done():
  176. if !ac.IsUndefined() {
  177. // Abort the Fetch request.
  178. ac.Call("abort")
  179. }
  180. return nil, req.Context().Err()
  181. case resp := <-respCh:
  182. return resp, nil
  183. case err := <-errCh:
  184. return nil, err
  185. }
  186. }
  187. var errClosed = errors.New("net/http: reader is closed")
  188. // streamReader implements an io.ReadCloser wrapper for ReadableStream.
  189. // See https://fetch.spec.whatwg.org/#readablestream for more information.
  190. type streamReader struct {
  191. pending []byte
  192. stream js.Value
  193. err error // sticky read error
  194. }
  195. func (r *streamReader) Read(p []byte) (n int, err error) {
  196. if r.err != nil {
  197. return 0, r.err
  198. }
  199. if len(r.pending) == 0 {
  200. var (
  201. bCh = make(chan []byte, 1)
  202. errCh = make(chan error, 1)
  203. )
  204. success := js.FuncOf(func(this js.Value, args []js.Value) any {
  205. result := args[0]
  206. if result.Get("done").Bool() {
  207. errCh <- io.EOF
  208. return nil
  209. }
  210. value := make([]byte, result.Get("value").Get("byteLength").Int())
  211. js.CopyBytesToGo(value, result.Get("value"))
  212. bCh <- value
  213. return nil
  214. })
  215. defer success.Release()
  216. failure := js.FuncOf(func(this js.Value, args []js.Value) any {
  217. // Assumes it's a TypeError. See
  218. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError
  219. // for more information on this type. See
  220. // https://streams.spec.whatwg.org/#byob-reader-read for the spec on
  221. // the read method.
  222. errCh <- errors.New(args[0].Get("message").String())
  223. return nil
  224. })
  225. defer failure.Release()
  226. r.stream.Call("read").Call("then", success, failure)
  227. select {
  228. case b := <-bCh:
  229. r.pending = b
  230. case err := <-errCh:
  231. r.err = err
  232. return 0, err
  233. }
  234. }
  235. n = copy(p, r.pending)
  236. r.pending = r.pending[n:]
  237. return n, nil
  238. }
  239. func (r *streamReader) Close() error {
  240. // This ignores any error returned from cancel method. So far, I did not encounter any concrete
  241. // situation where reporting the error is meaningful. Most users ignore error from resp.Body.Close().
  242. // If there's a need to report error here, it can be implemented and tested when that need comes up.
  243. r.stream.Call("cancel")
  244. if r.err == nil {
  245. r.err = errClosed
  246. }
  247. return nil
  248. }
  249. // arrayReader implements an io.ReadCloser wrapper for ArrayBuffer.
  250. // https://developer.mozilla.org/en-US/docs/Web/API/Body/arrayBuffer.
  251. type arrayReader struct {
  252. arrayPromise js.Value
  253. pending []byte
  254. read bool
  255. err error // sticky read error
  256. }
  257. func (r *arrayReader) Read(p []byte) (n int, err error) {
  258. if r.err != nil {
  259. return 0, r.err
  260. }
  261. if !r.read {
  262. r.read = true
  263. var (
  264. bCh = make(chan []byte, 1)
  265. errCh = make(chan error, 1)
  266. )
  267. success := js.FuncOf(func(this js.Value, args []js.Value) any {
  268. // Wrap the input ArrayBuffer with a Uint8Array
  269. uint8arrayWrapper := uint8Array.New(args[0])
  270. value := make([]byte, uint8arrayWrapper.Get("byteLength").Int())
  271. js.CopyBytesToGo(value, uint8arrayWrapper)
  272. bCh <- value
  273. return nil
  274. })
  275. defer success.Release()
  276. failure := js.FuncOf(func(this js.Value, args []js.Value) any {
  277. // Assumes it's a TypeError. See
  278. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError
  279. // for more information on this type.
  280. // See https://fetch.spec.whatwg.org/#concept-body-consume-body for reasons this might error.
  281. errCh <- errors.New(args[0].Get("message").String())
  282. return nil
  283. })
  284. defer failure.Release()
  285. r.arrayPromise.Call("then", success, failure)
  286. select {
  287. case b := <-bCh:
  288. r.pending = b
  289. case err := <-errCh:
  290. return 0, err
  291. }
  292. }
  293. if len(r.pending) == 0 {
  294. return 0, io.EOF
  295. }
  296. n = copy(p, r.pending)
  297. r.pending = r.pending[n:]
  298. return n, nil
  299. }
  300. func (r *arrayReader) Close() error {
  301. if r.err == nil {
  302. r.err = errClosed
  303. }
  304. return nil
  305. }