wasm-http-server/request.go

34 lines
678 B
Go
Raw Permalink Normal View History

package wasmhttp
2019-11-27 00:04:00 +01:00
import (
"bytes"
"net/http"
2021-01-24 21:18:18 +01:00
"net/http/httptest"
2019-11-27 00:04:00 +01:00
"syscall/js"
)
// Request builds and returns the equivalent http.Request
2021-01-27 23:06:28 +01:00
func Request(r js.Value) *http.Request {
jsBody := js.Global().Get("Uint8Array").New(Await(r.Call("arrayBuffer")))
2019-11-27 00:04:00 +01:00
body := make([]byte, jsBody.Get("length").Int())
js.CopyBytesToGo(body, jsBody)
2021-01-24 21:18:18 +01:00
req := httptest.NewRequest(
2020-05-28 23:44:27 +02:00
r.Get("method").String(),
r.Get("url").String(),
2019-11-27 00:04:00 +01:00
bytes.NewBuffer(body),
)
2020-05-28 23:44:27 +02:00
headersIt := r.Get("headers").Call("entries")
2019-11-27 00:19:46 +01:00
for {
2020-06-16 01:56:24 +02:00
e := headersIt.Call("next")
if e.Get("done").Bool() {
2019-11-27 00:19:46 +01:00
break
}
2020-06-16 01:56:24 +02:00
v := e.Get("value")
2019-11-27 00:19:46 +01:00
req.Header.Set(v.Index(0).String(), v.Index(1).String())
}
2021-01-27 23:06:28 +01:00
return req
2019-11-27 00:04:00 +01:00
}