From fa22eea00b56b354bb1b7e530e41b1604a16df38 Mon Sep 17 00:00:00 2001 From: syumai Date: Sun, 11 Feb 2024 23:12:28 +0900 Subject: [PATCH] split SetResponse func of Hono --- exp/hono/context.go | 11 +++++------ exp/hono/response.go | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 6 deletions(-) create mode 100644 exp/hono/response.go diff --git a/exp/hono/context.go b/exp/hono/context.go index 0b9aff3..8f78687 100644 --- a/exp/hono/context.go +++ b/exp/hono/context.go @@ -50,12 +50,11 @@ func (c *Context) ResponseBody() io.ReadCloser { } func (c *Context) SetBody(body io.ReadCloser) { - var bodyObj js.Value - if sr, ok := body.(jsutil.RawJSBodyGetter); ok { - bodyObj = sr.GetRawJSBody() - } else { - bodyObj = jsutil.ConvertReaderToReadableStream(body) - } + bodyObj := convertBodyToJS(body) respObj := c.ctxObj.Call("body", bodyObj) c.ctxObj.Set("res", respObj) } + +func (c *Context) SetResponse(respObj js.Value) { + c.ctxObj.Set("res", respObj) +} diff --git a/exp/hono/response.go b/exp/hono/response.go new file mode 100644 index 0000000..3089998 --- /dev/null +++ b/exp/hono/response.go @@ -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) +}