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/
|
node_modules/
|
||||||
*.wasm
|
*.wasm
|
||||||
|
!docs/**/*.wasm
|
||||||
|
46
index.js
46
index.js
@ -1,16 +1,36 @@
|
|||||||
self.wasmhttp = {
|
let nextHandlerId = 1
|
||||||
Serve: async (wasm) => {
|
const handlerResolvers = {}
|
||||||
const go = new Go()
|
|
||||||
const { instance } = await WebAssembly.instantiateStreaming(fetch(wasm), go.importObject)
|
|
||||||
try {
|
|
||||||
await go.run(instance)
|
|
||||||
} catch (e) {
|
|
||||||
console.error(e)
|
|
||||||
}
|
|
||||||
|
|
||||||
addEventListener('fetch', async e => {
|
const startWasm = async (wasm, WASMHTTP_HANDLER_ID, WASMHTTP_BASE) => {
|
||||||
if (new URL(e.request.url).pathname !== '/test') return
|
const go = new Go()
|
||||||
e.respondWith((await fetchHandler)(e.request))
|
go.env = {
|
||||||
})
|
WASMHTTP_HANDLER_ID,
|
||||||
|
WASMHTTP_BASE,
|
||||||
}
|
}
|
||||||
|
const { instance } = await WebAssembly.instantiateStreaming(fetch(wasm), go.importObject)
|
||||||
|
return go.run(instance)
|
||||||
|
}
|
||||||
|
|
||||||
|
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()
|
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
|
||||||
}
|
}
|
||||||
|
Loading…
x
Reference in New Issue
Block a user