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-22 19:10:47 +09:00
|
|
|
// 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
|
2023-02-22 19:10:47 +09:00
|
|
|
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
|
|
|
}
|
|
|
|
|
2023-02-22 19:10:47 +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
|
2023-02-22 19:10:47 +09:00
|
|
|
func ToHeader(headers js.Value) http.Header {
|
2023-02-23 23:20:21 +09:00
|
|
|
entries := jsutil.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
|
|
|
|
}
|
|
|
|
|
2023-02-22 19:10:47 +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
|
2023-02-22 19:10:47 +09:00
|
|
|
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
|
|
|
|
}
|
2023-02-22 19:10:47 +09:00
|
|
|
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,
|
2023-02-22 19:10:47 +09:00
|
|
|
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
|
|
|
|
}
|