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
|
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
|
|
|
|
}
|
2024-01-24 22:26:21 +09:00
|
|
|
return jsutil.ConvertReadableStreamToReadCloser(streamOrNull)
|
2022-05-18 00:04:37 +09:00
|
|
|
}
|
|
|
|
|
2023-02-22 19:10:47 +09:00
|
|
|
// ToRequest converts JavaScript sides Request to *http.Request.
|
2023-02-23 23:30:01 +09:00
|
|
|
// - Request: https://developer.mozilla.org/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
|
|
|
|
}
|
2023-02-23 23:29:22 +09:00
|
|
|
|
|
|
|
// ToJSRequest converts *http.Request to JavaScript sides Request.
|
2023-02-23 23:30:01 +09:00
|
|
|
// - Request: https://developer.mozilla.org/docs/Web/API/Request
|
2023-02-23 23:29:22 +09:00
|
|
|
func ToJSRequest(req *http.Request) js.Value {
|
|
|
|
jsReqOptions := jsutil.NewObject()
|
|
|
|
jsReqOptions.Set("method", req.Method)
|
|
|
|
jsReqOptions.Set("headers", ToJSHeader(req.Header))
|
|
|
|
jsReqBody := js.Undefined()
|
|
|
|
if req.Body != nil {
|
|
|
|
jsReqBody = jsutil.ConvertReaderToReadableStream(req.Body)
|
|
|
|
}
|
|
|
|
jsReqOptions.Set("body", jsReqBody)
|
|
|
|
jsReq := jsutil.RequestClass.New(req.URL.String(), jsReqOptions)
|
|
|
|
return jsReq
|
|
|
|
}
|