41 lines
790 B
Go
Raw Normal View History

2019-11-27 07:22:07 +01:00
package whutil
2019-11-27 00:04:00 +01:00
import (
"bytes"
"net/http"
"syscall/js"
)
// Request is a JS Request
2020-05-28 23:44:27 +02:00
type Request struct {
js.Value
}
2019-11-27 00:04:00 +01:00
2020-05-28 23:44:27 +02:00
// HTTPRequest builds and returns the equivalent http.Request
func (r Request) HTTPRequest() (*http.Request, error) {
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)
req, err := http.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),
)
if err != nil {
return nil, err
}
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
}