split workers.Ready and workers.WaitForCompletion from workers.Serve

This commit is contained in:
syumai 2024-11-08 01:46:52 +09:00
parent 6e29c1e9e5
commit 5f0fcb01dd
3 changed files with 35 additions and 5 deletions

View File

@ -58,4 +58,6 @@ func ScheduleTask(task Task) {
// ScheduleTaskNonBlock sets the Task to be executed but does not signal readiness or block
// indefinitely. The non-blocking form is meant to be used in conjunction with [workers.Serve].
func ScheduleTaskNonBlock(task Task) { scheduledTask = task }
func ScheduleTaskNonBlock(task Task) {
scheduledTask = task
}

View File

@ -25,3 +25,15 @@ func Serve(handler http.Handler) {
fmt.Fprintln(os.Stderr, "warn: this server is currently running in non-JS mode. to enable JS-related features, please use the make command in the syumai/workers template.")
http.ListenAndServe(addr, handler)
}
func ServeNonBlock(http.Handler) {
panic("ServeNonBlock is not supported in non-JS environments")
}
func Ready() {
panic("Ready is not supported in non-JS environments")
}
func WaitForCompletion() {
panic("WaitForCompletion is not supported in non-JS environments")
}

View File

@ -84,16 +84,32 @@ func handleRequest(reqObj js.Value) (js.Value, error) {
return w.ToJSResponse(), nil
}
//go:wasmimport workers ready
func ready()
// Server serves http.Handler on a JS runtime.
// Serve serves http.Handler on a JS runtime.
// if the given handler is nil, http.DefaultServeMux will be used.
func Serve(handler http.Handler) {
ServeNonBlock(handler)
Ready()
WaitForCompletion()
}
// ServeNonBlock sets the http.Handler to be served but does not signal readiness or block
// indefinitely. The non-blocking form is meant to be used in conjunction with Ready and WaitForCompletion.
func ServeNonBlock(handler http.Handler) {
if handler == nil {
handler = http.DefaultServeMux
}
httpHandler = handler
}
//go:wasmimport workers ready
func ready()
// Ready must be called after all setups of the Go side's handlers are done.
func Ready() {
ready()
}
// WaitForCompletion blocks until the handler set by ServeNonBlock is completed.
func WaitForCompletion() {
<-closeCh
}