2024-02-11 19:30:23 +09:00
|
|
|
package hono
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"io"
|
|
|
|
"net/http"
|
|
|
|
"sync"
|
|
|
|
"syscall/js"
|
|
|
|
|
|
|
|
"github.com/syumai/workers/internal/jshttp"
|
|
|
|
"github.com/syumai/workers/internal/jsutil"
|
|
|
|
"github.com/syumai/workers/internal/runtimecontext"
|
|
|
|
)
|
|
|
|
|
|
|
|
type Context struct {
|
|
|
|
ctxObj js.Value
|
|
|
|
reqFunc func() *http.Request
|
|
|
|
}
|
|
|
|
|
|
|
|
func newContext(ctxObj js.Value) *Context {
|
|
|
|
return &Context{
|
|
|
|
ctxObj: ctxObj,
|
|
|
|
reqFunc: sync.OnceValue(func() *http.Request {
|
|
|
|
reqObj := ctxObj.Get("req").Get("raw")
|
|
|
|
req, err := jshttp.ToRequest(reqObj)
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
ctx := runtimecontext.New(context.Background(), reqObj, jsutil.RuntimeContext)
|
|
|
|
req = req.WithContext(ctx)
|
|
|
|
return req
|
|
|
|
}),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Context) Request() *http.Request {
|
|
|
|
return c.reqFunc()
|
|
|
|
}
|
|
|
|
|
2024-02-11 21:55:49 +09:00
|
|
|
func (c *Context) SetHeader(key, value string) {
|
|
|
|
c.ctxObj.Call("header", key, value)
|
2024-02-11 19:30:23 +09:00
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Context) SetStatus(statusCode int) {
|
|
|
|
c.ctxObj.Call("status", statusCode)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Context) ResponseBody() io.ReadCloser {
|
|
|
|
return jsutil.ConvertReadableStreamToReadCloser(c.ctxObj.Get("res").Get("body"))
|
|
|
|
}
|
|
|
|
|
2024-02-11 21:55:49 +09:00
|
|
|
func (c *Context) SetBody(body io.ReadCloser) {
|
2024-02-11 23:12:28 +09:00
|
|
|
bodyObj := convertBodyToJS(body)
|
2024-02-11 21:55:49 +09:00
|
|
|
respObj := c.ctxObj.Call("body", bodyObj)
|
|
|
|
c.ctxObj.Set("res", respObj)
|
2024-02-11 19:30:23 +09:00
|
|
|
}
|
2024-02-11 23:12:28 +09:00
|
|
|
|
|
|
|
func (c *Context) SetResponse(respObj js.Value) {
|
|
|
|
c.ctxObj.Set("res", respObj)
|
|
|
|
}
|