cloudflare-workers/handler.go

82 lines
1.9 KiB
Go
Raw Normal View History

2022-05-18 00:04:37 +09:00
package workers
import (
2023-02-11 10:30:51 +09:00
"context"
2022-05-18 00:04:37 +09:00
"fmt"
"io"
"net/http"
"syscall/js"
2022-09-13 23:18:17 +09:00
"github.com/syumai/workers/internal/jsutil"
2023-02-11 10:30:51 +09:00
"github.com/syumai/workers/internal/runtimecontext"
2022-05-18 00:04:37 +09:00
)
var httpHandler http.Handler
func init() {
var handleRequestCallback js.Func
handleRequestCallback = js.FuncOf(func(this js.Value, args []js.Value) any {
2023-02-11 10:30:51 +09:00
if len(args) > 2 {
2022-05-18 00:04:37 +09:00
panic(fmt.Errorf("too many args given to handleRequest: %d", len(args)))
}
2023-02-11 10:30:51 +09:00
reqObj := args[0]
runtimeCtxObj := js.Null()
if len(args) > 1 {
runtimeCtxObj = args[1]
}
2022-05-18 00:04:37 +09:00
var cb js.Func
cb = js.FuncOf(func(_ js.Value, pArgs []js.Value) any {
defer cb.Release()
resolve := pArgs[0]
go func() {
2023-02-11 10:30:51 +09:00
res, err := handleRequest(reqObj, runtimeCtxObj)
2022-05-18 00:04:37 +09:00
if err != nil {
panic(err)
}
resolve.Invoke(res)
}()
return js.Undefined()
})
2022-09-13 23:18:17 +09:00
return jsutil.NewPromise(cb)
2022-05-18 00:04:37 +09:00
})
2022-09-13 23:18:17 +09:00
jsutil.Global.Set("handleRequest", handleRequestCallback)
2022-05-18 00:04:37 +09:00
}
// handleRequest accepts a Request object and returns Response object.
2023-02-11 10:30:51 +09:00
func handleRequest(reqObj js.Value, runtimeCtxObj js.Value) (js.Value, error) {
2022-05-18 00:04:37 +09:00
if httpHandler == nil {
return js.Value{}, fmt.Errorf("Serve must be called before handleRequest.")
}
req, err := toRequest(reqObj)
if err != nil {
panic(err)
}
2023-02-11 10:30:51 +09:00
ctx := runtimecontext.New(context.Background(), runtimeCtxObj)
req = req.WithContext(ctx)
2022-05-18 00:04:37 +09:00
reader, writer := io.Pipe()
w := &responseWriterBuffer{
header: http.Header{},
statusCode: http.StatusOK,
2022-05-20 00:11:47 +09:00
reader: reader,
writer: writer,
readyCh: make(chan struct{}),
2022-05-18 00:04:37 +09:00
}
go func() {
2022-05-20 00:11:47 +09:00
defer w.ready()
2022-05-18 00:04:37 +09:00
defer writer.Close()
httpHandler.ServeHTTP(w, req)
}()
2022-05-20 00:11:47 +09:00
return toJSResponse(w)
2022-05-18 00:04:37 +09:00
}
// Server serves http.Handler on Cloudflare Workers.
// if the given handler is nil, http.DefaultServeMux will be used.
func Serve(handler http.Handler) {
if handler == nil {
handler = http.DefaultServeMux
}
httpHandler = handler
2022-11-19 23:22:04 +09:00
jsutil.Global.Call("ready")
2022-05-18 00:04:37 +09:00
select {}
}