This commit is contained in:
Nicolas Lepage 2021-01-22 00:58:30 +01:00
parent f475080c4a
commit b174389005
No known key found for this signature in database
GPG Key ID: B0879E35E66D8F6F
3 changed files with 17 additions and 35 deletions

Binary file not shown.

View File

@ -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 + "/"
}
if path != "" { // FIXME always true since / suffix is added to path
var prefix = os.Getenv("WASMHTTP_PATH")
var prefix = js.Global().Get("wasmhttp").Get("path").String()
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
}

34
sw.js
View File

@ -1,36 +1,24 @@
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())
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 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]
// FIXME await ? catch ?
wasmPromise
.then(wasm => WebAssembly.instantiate(wasm, go.importObject))
.then(({ instance }) => go.run(instance))
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
e.respondWith(handlerPromise.then(handler => handler(e.request)))
})