2023-02-23 23:20:21 +09:00
|
|
|
package jshttp
|
2023-02-22 19:10:47 +09:00
|
|
|
|
|
|
|
import (
|
2023-02-23 23:29:22 +09:00
|
|
|
"io"
|
2023-02-22 19:10:47 +09:00
|
|
|
"net/http"
|
2023-02-23 23:29:22 +09:00
|
|
|
"strconv"
|
|
|
|
"strings"
|
2023-02-22 19:10:47 +09:00
|
|
|
"syscall/js"
|
2023-02-23 23:20:21 +09:00
|
|
|
|
|
|
|
"github.com/syumai/workers/internal/jsutil"
|
2023-02-22 19:10:47 +09:00
|
|
|
)
|
|
|
|
|
2023-02-23 23:29:22 +09:00
|
|
|
// ToResponse converts JavaScript sides Response to *http.Response.
|
2023-02-23 23:30:01 +09:00
|
|
|
// - Response: https://developer.mozilla.org/docs/Web/API/Response
|
2023-02-23 23:29:22 +09:00
|
|
|
func ToResponse(res js.Value) (*http.Response, error) {
|
|
|
|
status := res.Get("status").Int()
|
|
|
|
promise := res.Call("text")
|
|
|
|
body, err := jsutil.AwaitPromise(promise)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
header := ToHeader(res.Get("headers"))
|
|
|
|
contentLength, _ := strconv.ParseInt(header.Get("Content-Length"), 10, 64)
|
|
|
|
|
|
|
|
return &http.Response{
|
|
|
|
Status: strconv.Itoa(status) + " " + res.Get("statusText").String(),
|
|
|
|
StatusCode: status,
|
|
|
|
Header: header,
|
|
|
|
Body: io.NopCloser(strings.NewReader(body.String())),
|
|
|
|
ContentLength: contentLength,
|
|
|
|
}, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// ToJSResponse converts *http.Response to JavaScript sides Response.
|
2023-02-23 23:30:01 +09:00
|
|
|
// - Response: https://developer.mozilla.org/docs/Web/API/Response
|
2023-02-22 19:10:47 +09:00
|
|
|
func ToJSResponse(w *ResponseWriterBuffer) (js.Value, error) {
|
2023-02-22 19:23:56 +09:00
|
|
|
<-w.ReadyCh // wait until ready
|
|
|
|
status := w.StatusCode
|
2023-02-22 19:10:47 +09:00
|
|
|
if status == 0 {
|
|
|
|
status = http.StatusOK
|
|
|
|
}
|
2023-02-23 23:20:21 +09:00
|
|
|
respInit := jsutil.NewObject()
|
2023-02-22 19:10:47 +09:00
|
|
|
respInit.Set("status", status)
|
|
|
|
respInit.Set("statusText", http.StatusText(status))
|
|
|
|
respInit.Set("headers", ToJSHeader(w.Header()))
|
2023-04-26 12:56:33 +09:00
|
|
|
if status == http.StatusSwitchingProtocols ||
|
|
|
|
status == http.StatusNoContent ||
|
|
|
|
status == http.StatusResetContent ||
|
|
|
|
status == http.StatusNotModified {
|
|
|
|
return jsutil.ResponseClass.New(jsutil.Null, respInit), nil
|
|
|
|
}
|
2023-02-23 23:20:21 +09:00
|
|
|
readableStream := jsutil.ConvertReaderToReadableStream(w.Reader)
|
|
|
|
return jsutil.ResponseClass.New(readableStream, respInit), nil
|
2023-02-22 19:10:47 +09:00
|
|
|
}
|