This commit is contained in:
Nicolas Lepage 2021-01-22 01:25:50 +01:00
parent 889c33097f
commit d1781bb693
No known key found for this signature in database
GPG Key ID: B0879E35E66D8F6F
5 changed files with 42 additions and 10 deletions

View File

@ -1,7 +1,6 @@
package main package main
import ( import (
"context"
"encoding/json" "encoding/json"
"fmt" "fmt"
"net/http" "net/http"
@ -10,7 +9,7 @@ import (
) )
func main() { func main() {
defer fmt.Println("api stopping...") defer fmt.Println("api stopped...")
http.HandleFunc("/hello", func(res http.ResponseWriter, req *http.Request) { http.HandleFunc("/hello", func(res http.ResponseWriter, req *http.Request) {
params := make(map[string]string) params := make(map[string]string)
@ -25,8 +24,5 @@ func main() {
} }
}) })
var release = wasmhttp.Serve(nil) wasmhttp.Serve(nil)
defer release()
<-context.Background().Done()
} }

Binary file not shown.

View File

@ -8,4 +8,4 @@ addEventListener('activate', event => {
event.waitUntil(clients.claim()) event.waitUntil(clients.claim())
}) })
registerWasmHTTPListener('api.wasm', 'api') registerWasmHTTPListener('api.wasm', { base: 'api' })

View File

@ -1,6 +1,7 @@
package wasmhttp package wasmhttp
import ( import (
"context"
"fmt" "fmt"
"net/http" "net/http"
"strings" "strings"
@ -10,7 +11,7 @@ import (
) )
// Serve serves HTTP requests using handler or http.DefaultServeMux if handler is nil. // Serve serves HTTP requests using handler or http.DefaultServeMux if handler is nil.
func Serve(handler http.Handler) func() { func Serve(handler http.Handler) {
var h = handler var h = handler
if h == nil { if h == nil {
h = http.DefaultServeMux h = http.DefaultServeMux
@ -57,8 +58,27 @@ func Serve(handler http.Handler) func() {
return resPromise return resPromise
}) })
defer cb.Release()
js.Global().Get("wasmhttp").Call("setHandler", cb) js.Global().Get("wasmhttp").Call("setHandler", cb)
return cb.Release <-Context().Done()
}
func Context() context.Context {
var timeoutPromise = js.Global().Get("wasmhttp").Get("timeoutPromise")
if timeoutPromise.IsUndefined() {
return context.Background()
}
var ctx, cancel = context.WithCancel(context.Background())
go func() {
whutil.Promise{timeoutPromise}.Await()
cancel()
}()
return ctx
} }

18
sw.js
View File

@ -1,13 +1,27 @@
importScripts('https://cdn.jsdelivr.net/gh/golang/go@go1.15.7/misc/wasm/wasm_exec.js') importScripts('https://cdn.jsdelivr.net/gh/golang/go@go1.15.7/misc/wasm/wasm_exec.js')
function registerWasmHTTPListener(wasm, base, args = []) { function registerWasmHTTPListener(wasm, { base, args = [], timeout = 25 } = {}) {
let path = new URL(registration.scope).pathname let path = new URL(registration.scope).pathname
if (base && base !== '') path = `${trimEnd(path, '/')}/${trimStart(base, '/')}` if (base && base !== '') path = `${trimEnd(path, '/')}/${trimStart(base, '/')}`
let timeoutPromise
let resetTimeout
if (timeout) {
let resolveTimeout
timeoutPromise = new Promise(resolve => { resolveTimeout = resolve })
let timeoutId
resetTimeout = () => {
clearTimeout(timeoutId)
timeoutId = setTimeout(resolveTimeout, timeout * 1000)
}
resetTimeout()
}
const handlerPromise = new Promise(setHandler => { const handlerPromise = new Promise(setHandler => {
self.wasmhttp = { self.wasmhttp = {
path, path,
setHandler, setHandler,
timeoutPromise,
} }
}) })
@ -16,6 +30,8 @@ function registerWasmHTTPListener(wasm, base, args = []) {
WebAssembly.instantiateStreaming(fetch(wasm), go.importObject).then(({ instance }) => go.run(instance)) WebAssembly.instantiateStreaming(fetch(wasm), go.importObject).then(({ instance }) => go.run(instance))
addEventListener('fetch', e => { addEventListener('fetch', e => {
resetTimeout?.()
const { pathname } = new URL(e.request.url) const { pathname } = new URL(e.request.url)
if (!pathname.startsWith(path)) return if (!pathname.startsWith(path)) return