mirror of
https://github.com/nlepage/go-wasm-http-server.git
synced 2025-03-11 09:39:10 +00:00
⚗️
This commit is contained in:
parent
272c6d8876
commit
cf2a3ceefa
18
sw.js
18
sw.js
@ -15,30 +15,26 @@ function registerWasmHTTPListener(wasm, base, args) {
|
|||||||
let path = new URL(registration.scope).pathname
|
let path = new URL(registration.scope).pathname
|
||||||
if (base && base !== '') path = `${trimEnd(path, '/')}/${trimStart(base, '/')}`
|
if (base && base !== '') path = `${trimEnd(path, '/')}/${trimStart(base, '/')}`
|
||||||
|
|
||||||
|
const wasmPromise = fetch(wasm)
|
||||||
|
|
||||||
addEventListener('fetch', e => {
|
addEventListener('fetch', e => {
|
||||||
const { pathname } = new URL(e.request.url)
|
const { pathname } = new URL(e.request.url)
|
||||||
if (!pathname.startsWith(path)) return
|
if (!pathname.startsWith(path)) return
|
||||||
|
|
||||||
console.log(`FetchEvent ${pathname}`)
|
|
||||||
|
|
||||||
const handlerId = `${nextHandlerId++}`
|
const handlerId = `${nextHandlerId++}`
|
||||||
const handlerPromise = new Promise(resolve => handlerResolvers[handlerId] = resolve)
|
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]
|
||||||
|
const { instance } = await WebAssembly.instantiateStreaming(wasmPromise, go.importObject)
|
||||||
// FIXME await ? catch ?
|
// FIXME await ? catch ?
|
||||||
startWasm(wasm, { env: { WASMHTTP_HANDLER_ID: handlerId, WASMHTTP_PATH: path }, args })
|
go.run(instance)
|
||||||
|
|
||||||
e.respondWith(handlerPromise.then(handler => handler(e.request)))
|
e.respondWith(handlerPromise.then(handler => handler(e.request)))
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
async function startWasm(wasm, { env, args = [] }) {
|
|
||||||
const go = new Go()
|
|
||||||
go.env = env
|
|
||||||
go.argv = [wasm, ...args]
|
|
||||||
const { instance } = await WebAssembly.instantiateStreaming(fetch(wasm), go.importObject)
|
|
||||||
return go.run(instance)
|
|
||||||
}
|
|
||||||
|
|
||||||
function trimStart(s, c) {
|
function trimStart(s, c) {
|
||||||
let r = s
|
let r = s
|
||||||
while (r.startsWith(c)) r = r.slice(c.length)
|
while (r.startsWith(c)) r = r.slice(c.length)
|
||||||
|
Loading…
x
Reference in New Issue
Block a user