This commit is contained in:
Nicolas Lepage 2019-11-27 08:53:34 +01:00
parent 6049930e90
commit 5a9f7c57a2
No known key found for this signature in database
GPG Key ID: B0879E35E66D8F6F
3 changed files with 35 additions and 14 deletions

1
.gitignore vendored
View File

@ -1,2 +1,3 @@
node_modules/ node_modules/
*.wasm *.wasm
!docs/**/*.wasm

View File

@ -1,16 +1,36 @@
self.wasmhttp = { let nextHandlerId = 1
Serve: async (wasm) => { const handlerResolvers = {}
const startWasm = async (wasm, WASMHTTP_HANDLER_ID, WASMHTTP_BASE) => {
const go = new Go() const go = new Go()
go.env = {
WASMHTTP_HANDLER_ID,
WASMHTTP_BASE,
}
const { instance } = await WebAssembly.instantiateStreaming(fetch(wasm), go.importObject) const { instance } = await WebAssembly.instantiateStreaming(fetch(wasm), go.importObject)
try { return go.run(instance)
await go.run(instance)
} catch (e) {
console.error(e)
} }
addEventListener('fetch', async e => { self.wasmhttp = {
if (new URL(e.request.url).pathname !== '/test') return serve: async ({ wasm, base } = {
e.respondWith((await fetchHandler)(e.request)) base: '',
}) }) => {
try {
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)))
} catch (e) {
console.error('wasmhttp: error:', e)
} }
},
registerHandler: (handlerId, handler) => {
handlerResolvers[handlerId](handler)
delete handlerResolvers[handlerId]
},
} }

View File

@ -55,7 +55,7 @@ func Serve(handler http.Handler) func() {
return res.Value() return res.Value()
}) })
js.Global().Get("wasmhttp").Call("RegisterHandler", os.Getenv("WASMHTTP_HANDLER_ID"), cb) js.Global().Get("wasmhttp").Call("registerHandler", os.Getenv("WASMHTTP_HANDLER_ID"), cb)
return cb.Release return cb.Release
} }