mirror of
https://github.com/nlepage/go-wasm-http-server.git
synced 2025-03-10 09:27:08 +00:00
🚧
This commit is contained in:
parent
6049930e90
commit
5a9f7c57a2
1
.gitignore
vendored
1
.gitignore
vendored
@ -1,2 +1,3 @@
|
||||
node_modules/
|
||||
*.wasm
|
||||
!docs/**/*.wasm
|
||||
|
40
index.js
40
index.js
@ -1,16 +1,36 @@
|
||||
self.wasmhttp = {
|
||||
Serve: async (wasm) => {
|
||||
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)
|
||||
try {
|
||||
await go.run(instance)
|
||||
} catch (e) {
|
||||
console.error(e)
|
||||
return go.run(instance)
|
||||
}
|
||||
|
||||
addEventListener('fetch', async e => {
|
||||
if (new URL(e.request.url).pathname !== '/test') return
|
||||
e.respondWith((await fetchHandler)(e.request))
|
||||
})
|
||||
self.wasmhttp = {
|
||||
serve: async ({ wasm, base } = {
|
||||
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]
|
||||
},
|
||||
}
|
||||
|
2
serve.go
2
serve.go
@ -55,7 +55,7 @@ func Serve(handler http.Handler) func() {
|
||||
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
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user