2021-01-24 18:03:17 +01:00
|
|
|
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"
|
|
|
|
)
|
|
|
|
|
2021-01-24 18:03:17 +01:00
|
|
|
// Request builds and returns the equivalent http.Request
|
|
|
|
func Request(r js.Value) (*http.Request, error) {
|
2020-05-28 23:44:27 +02:00
|
|
|
jsBody := js.Global().Get("Uint8Array").New(Promise{r.Call("arrayBuffer")}.Await())
|
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())
|
|
|
|
}
|
|
|
|
|
2019-11-27 00:04:00 +01:00
|
|
|
return req, nil
|
|
|
|
}
|