diff --git a/docs/api.wasm b/docs/api.wasm index 6d697eb..46b3538 100755 Binary files a/docs/api.wasm and b/docs/api.wasm differ diff --git a/serve.go b/serve.go index 56f990d..031d493 100644 --- a/serve.go +++ b/serve.go @@ -3,7 +3,6 @@ package wasmhttp import ( "fmt" "net/http" - "os" "strings" "syscall/js" @@ -17,19 +16,14 @@ func Serve(handler http.Handler) func() { h = http.DefaultServeMux } - var path = os.Getenv("WASMHTTP_PATH") - if !strings.HasSuffix(path, "/") { - path = path + "/" + var prefix = js.Global().Get("wasmhttp").Get("path").String() + for strings.HasSuffix(prefix, "/") { + prefix = strings.TrimSuffix(prefix, "/") } - if path != "" { // FIXME always true since / suffix is added to path - var prefix = os.Getenv("WASMHTTP_PATH") - for strings.HasSuffix(prefix, "/") { - prefix = strings.TrimSuffix(prefix, "/") - } - + if prefix != "" { var mux = http.NewServeMux() - mux.Handle(path, http.StripPrefix(prefix, h)) + mux.Handle(prefix+"/", http.StripPrefix(prefix, h)) h = mux } @@ -64,7 +58,7 @@ func Serve(handler http.Handler) func() { return resPromise }) - js.Global().Get("wasmhttp").Call("registerHandler", os.Getenv("WASMHTTP_HANDLER_ID"), cb) + js.Global().Get("wasmhttp").Call("setHandler", cb) return cb.Release } diff --git a/sw.js b/sw.js index c2e1927..d777926 100644 --- a/sw.js +++ b/sw.js @@ -1,37 +1,25 @@ importScripts('https://cdn.jsdelivr.net/gh/golang/go@go1.15.7/misc/wasm/wasm_exec.js') -let nextHandlerId = 1 -const handlerResolvers = {} -const handlers = [] - -self.wasmhttp = { - registerHandler: (handlerId, handler) => { - handlerResolvers[handlerId](handler) - delete handlerResolvers[handlerId] - }, -} - function registerWasmHTTPListener(wasm, base, args = []) { let path = new URL(registration.scope).pathname if (base && base !== '') path = `${trimEnd(path, '/')}/${trimStart(base, '/')}` - const wasmPromise = fetch(wasm).then(res => res.arrayBuffer()) + const handlerPromise = new Promise(setHandler => { + self.wasmhttp = { + path, + setHandler, + } + }) + + const go = new Go() + go.env = { WASMHTTP_HANDLER_ID: handlerId, WASMHTTP_PATH: path } + go.argv = [wasm, ...args] + WebAssembly.instantiateStreaming(fetch(wasm), go.importObject).then(({ instance }) => go.run(instance)) addEventListener('fetch', e => { const { pathname } = new URL(e.request.url) if (!pathname.startsWith(path)) return - const handlerId = `${nextHandlerId++}` - const handlerPromise = new Promise(resolve => handlerResolvers[handlerId] = resolve) - - const go = new Go() - go.env = { WASMHTTP_HANDLER_ID: handlerId, WASMHTTP_PATH: path } - go.argv = [wasm, ...args] - // FIXME await ? catch ? - wasmPromise - .then(wasm => WebAssembly.instantiate(wasm, go.importObject)) - .then(({ instance }) => go.run(instance)) - e.respondWith(handlerPromise.then(handler => handler(e.request))) }) }