split SetResponse func of Hono

This commit is contained in:
syumai 2024-02-11 23:12:28 +09:00
parent bd88dd6151
commit fa22eea00b
2 changed files with 40 additions and 6 deletions

View File

@ -50,12 +50,11 @@ func (c *Context) ResponseBody() io.ReadCloser {
} }
func (c *Context) SetBody(body io.ReadCloser) { func (c *Context) SetBody(body io.ReadCloser) {
var bodyObj js.Value bodyObj := convertBodyToJS(body)
if sr, ok := body.(jsutil.RawJSBodyGetter); ok {
bodyObj = sr.GetRawJSBody()
} else {
bodyObj = jsutil.ConvertReaderToReadableStream(body)
}
respObj := c.ctxObj.Call("body", bodyObj) respObj := c.ctxObj.Call("body", bodyObj)
c.ctxObj.Set("res", respObj) c.ctxObj.Set("res", respObj)
} }
func (c *Context) SetResponse(respObj js.Value) {
c.ctxObj.Set("res", respObj)
}

35
exp/hono/response.go Normal file
View File

@ -0,0 +1,35 @@
package hono
import (
"io"
"net/http"
"syscall/js"
"github.com/syumai/workers/internal/jshttp"
"github.com/syumai/workers/internal/jsutil"
)
func convertBodyToJS(body io.ReadCloser) js.Value {
if sr, ok := body.(jsutil.RawJSBodyGetter); ok {
return sr.GetRawJSBody()
}
return jsutil.ConvertReaderToReadableStream(body)
}
func NewJSResponse(body io.ReadCloser, statusCode int, headers http.Header) js.Value {
bodyObj := convertBodyToJS(body)
opts := jsutil.ObjectClass.New()
if statusCode != 0 {
opts.Set("status", statusCode)
}
if headers != nil {
headersObj := jshttp.ToJSHeader(headers)
opts.Set("headers", headersObj)
}
return jsutil.ResponseClass.New(bodyObj, opts)
}
func NewJSResponseWithBase(body io.ReadCloser, baseRespObj js.Value) js.Value {
bodyObj := convertBodyToJS(body)
return jsutil.ResponseClass.New(bodyObj, baseRespObj)
}