use go:wasmimport for ready func

This commit is contained in:
syumai 2024-01-04 22:59:05 +09:00
parent 1f1d7bc2f1
commit fb6e3ca7a4
2 changed files with 14 additions and 5 deletions

View File

@ -13,7 +13,7 @@ globalThis.tryCatch = (fn) => {
} catch(e) { } catch(e) {
return { return {
error: e, error: e,
} };
} }
} }
@ -22,10 +22,16 @@ export function init(m) {
} }
async function run() { async function run() {
let ready;
const readyPromise = new Promise((resolve) => { const readyPromise = new Promise((resolve) => {
globalThis.ready = resolve; ready = resolve;
});
const instance = new WebAssembly.Instance(mod, {
...go.importObject,
workers: {
ready: () => { ready() }
},
}); });
const instance = new WebAssembly.Instance(mod, go.importObject);
go.run(instance); go.run(instance);
await readyPromise; await readyPromise;
} }
@ -35,7 +41,7 @@ function createRuntimeContext(env, ctx) {
env, env,
ctx, ctx,
connect, connect,
} };
} }
export async function fetch(req, env, ctx) { export async function fetch(req, env, ctx) {

View File

@ -71,6 +71,9 @@ func handleRequest(reqObj js.Value, runtimeCtxObj js.Value) (js.Value, error) {
return w.ToJSResponse(), nil return w.ToJSResponse(), nil
} }
//go:wasmimport workers ready
func ready()
// Server serves http.Handler on Cloudflare Workers. // Server serves http.Handler on Cloudflare Workers.
// if the given handler is nil, http.DefaultServeMux will be used. // if the given handler is nil, http.DefaultServeMux will be used.
func Serve(handler http.Handler) { func Serve(handler http.Handler) {
@ -78,6 +81,6 @@ func Serve(handler http.Handler) {
handler = http.DefaultServeMux handler = http.DefaultServeMux
} }
httpHandler = handler httpHandler = handler
js.Global().Call("ready") ready()
select {} select {}
} }