48 lines
1.3 KiB
JavaScript
Raw Normal View History

importScripts('https://cdn.jsdelivr.net/gh/golang/go@go1.15.7/misc/wasm/wasm_exec.js')
2019-11-27 08:53:34 +01:00
2019-12-02 16:52:40 +01:00
let nextHandlerId = 1
const handlerResolvers = {}
const handlers = []
2019-11-27 01:12:09 +01:00
2019-12-02 16:52:40 +01:00
self.wasmhttp = {
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
}
2019-12-02 16:52:40 +01:00
2021-01-22 00:05:38 +01:00
function registerWasmHTTPListener(wasm, base, args = []) {
2021-01-21 23:07:42 +01:00
let path = new URL(registration.scope).pathname
if (base && base !== '') path = `${trimEnd(path, '/')}/${trimStart(base, '/')}`
2021-01-22 00:14:22 +01:00
const wasmPromise = fetch(wasm).then(res => res.arrayBuffer())
2021-01-21 23:59:35 +01:00
2021-01-21 23:28:52 +01:00
addEventListener('fetch', e => {
2021-01-21 23:07:42 +01:00
const { pathname } = new URL(e.request.url)
if (!pathname.startsWith(path)) return
const handlerId = `${nextHandlerId++}`
const handlerPromise = new Promise(resolve => handlerResolvers[handlerId] = resolve)
2021-01-21 23:59:35 +01:00
const go = new Go()
go.env = { WASMHTTP_HANDLER_ID: handlerId, WASMHTTP_PATH: path }
go.argv = [wasm, ...args]
2021-01-21 23:07:42 +01:00
// FIXME await ? catch ?
2021-01-22 00:14:22 +01:00
WebAssembly.instantiate(wasmPromise, go.importObject).then(({ instance }) => go.run(instance))
2021-01-21 23:59:35 +01:00
2021-01-21 23:28:52 +01:00
e.respondWith(handlerPromise.then(handler => handler(e.request)))
2021-01-21 23:07:42 +01:00
})
2021-01-21 23:23:27 +01:00
}
function trimStart(s, c) {
let r = s
while (r.startsWith(c)) r = r.slice(c.length)
return r
}
function trimEnd(s, c) {
let r = s
while (r.endsWith(c)) r = r.slice(0, -c.length)
return r
}