Files
wasm-http-server/index.js

37 lines
940 B
JavaScript
Raw Normal View History

2019-11-27 08:53:34 +01:00
let nextHandlerId = 1
const handlerResolvers = {}
const startWasm = async (wasm, WASMHTTP_HANDLER_ID, WASMHTTP_BASE) => {
const go = new Go()
go.env = {
WASMHTTP_HANDLER_ID,
WASMHTTP_BASE,
}
const { instance } = await WebAssembly.instantiateStreaming(fetch(wasm), go.importObject)
return go.run(instance)
}
2019-11-27 01:12:09 +01:00
self.wasmhttp = {
2019-11-27 08:53:34 +01:00
serve: async ({ wasm, base } = {
base: '',
}) => {
2019-11-27 01:12:09 +01:00
try {
2019-11-27 08:53:34 +01:00
if (!wasm) throw TypeError('option.wasm must be defined')
const handlerId = `${nextHandlerId++}`
const handler = new Promise(resolve => handlerResolvers[handlerId] = resolve)
startWasm(wasm, handlerId, base)
addEventListener('fetch', async e => e.respondWith((await handler)(e.request)))
2019-11-27 01:12:09 +01:00
} catch (e) {
2019-11-27 08:53:34 +01:00
console.error('wasmhttp: error:', e)
2019-11-27 01:12:09 +01:00
}
2019-11-27 08:53:34 +01:00
},
2019-11-27 01:12:09 +01:00
2019-11-27 08:53:34 +01:00
registerHandler: (handlerId, handler) => {
handlerResolvers[handlerId](handler)
delete handlerResolvers[handlerId]
},
2019-11-27 01:12:09 +01:00
}