60 lines
1.7 KiB
Go
Raw Normal View History

package jsutil
2022-05-18 00:04:37 +09:00
import (
"io"
"net/http"
"net/url"
"strconv"
"strings"
"syscall/js"
)
// ToBody converts JavaScripts sides ReadableStream (can be null) to io.ReadCloser.
2022-08-03 00:19:01 +09:00
// - ReadableStream: https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream
func ToBody(streamOrNull js.Value) io.ReadCloser {
2022-05-18 00:04:37 +09:00
if streamOrNull.IsNull() {
return nil
}
sr := streamOrNull.Call("getReader")
return io.NopCloser(ConvertStreamReaderToReader(sr))
2022-05-18 00:04:37 +09:00
}
// ToHeader converts JavaScript sides Headers to http.Header.
2022-08-03 00:19:01 +09:00
// - Headers: https://developer.mozilla.org/ja/docs/Web/API/Headers
func ToHeader(headers js.Value) http.Header {
entries := ArrayFrom(headers.Call("entries"))
2022-05-18 00:04:37 +09:00
headerLen := entries.Length()
h := http.Header{}
for i := 0; i < headerLen; i++ {
entry := entries.Index(i)
key := entry.Index(0).String()
2022-05-20 00:11:47 +09:00
values := entry.Index(1).String()
for _, value := range strings.Split(values, ",") {
h.Add(key, value)
}
2022-05-18 00:04:37 +09:00
}
return h
}
// ToRequest converts JavaScript sides Request to *http.Request.
2022-08-03 00:19:01 +09:00
// - Request: https://developer.mozilla.org/ja/docs/Web/API/Request
func ToRequest(req js.Value) (*http.Request, error) {
2022-05-18 00:04:37 +09:00
reqUrl, err := url.Parse(req.Get("url").String())
if err != nil {
return nil, err
}
header := ToHeader(req.Get("headers"))
2022-05-18 00:04:37 +09:00
// ignore err
contentLength, _ := strconv.ParseInt(header.Get("Content-Length"), 10, 64)
return &http.Request{
Method: req.Get("method").String(),
URL: reqUrl,
Header: header,
Body: ToBody(req.Get("body")),
2022-05-18 00:04:37 +09:00
ContentLength: contentLength,
TransferEncoding: strings.Split(header.Get("Transfer-Encoding"), ","),
Host: header.Get("Host"),
}, nil
}