45 lines
1.2 KiB
Go
Raw Normal View History

2023-02-23 23:20:21 +09:00
package jshttp
2022-05-18 00:04:37 +09:00
import (
"io"
"net/http"
"net/url"
"strconv"
"strings"
"syscall/js"
2023-02-23 23:20:21 +09:00
"github.com/syumai/workers/internal/jsutil"
2022-05-18 00:04:37 +09:00
)
2023-02-23 23:25:43 +09:00
// ToBody converts JavaScript 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")
2023-02-23 23:20:21 +09:00
return io.NopCloser(jsutil.ConvertStreamReaderToReader(sr))
2022-05-18 00:04:37 +09:00
}
// 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
}