This commit is contained in:
Nicolas Lepage 2021-01-22 00:42:01 +01:00
parent 8369104f08
commit f475080c4a
No known key found for this signature in database
GPG Key ID: B0879E35E66D8F6F
4 changed files with 6 additions and 67 deletions

View File

@ -1,6 +1,7 @@
package main
import (
"context"
"encoding/json"
"fmt"
"net/http"
@ -24,5 +25,8 @@ func main() {
}
})
wasmhttp.ServeOnce(nil)
var release = wasmhttp.Serve(nil)
defer release()
<-context.Background().Done()
}

Binary file not shown.

View File

@ -19,7 +19,7 @@
</script>
</head>
<body>
<label for="name">Name : </label><input id="name" value="World">
<label for="name">Name: </label><input id="name" value="World">
<button onclick="hello()">Hello</button>
</body>
</html>

View File

@ -1,7 +1,6 @@
package wasmhttp
import (
"context"
"fmt"
"net/http"
"os"
@ -69,67 +68,3 @@ func Serve(handler http.Handler) func() {
return cb.Release
}
func ServeOnce(handler http.Handler) {
var ctx, cancel = context.WithCancel(context.Background())
var h = handler
if h == nil {
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")
for strings.HasSuffix(prefix, "/") {
prefix = strings.TrimSuffix(prefix, "/")
}
var mux = http.NewServeMux()
mux.Handle(path, http.StripPrefix(prefix, h))
h = mux
}
var cb = js.FuncOf(func(_ js.Value, args []js.Value) interface{} {
var jsReq = whutil.Request{args[0]}
var resPromise = whutil.NewPromise(func(resolve whutil.PromiseResolve, reject whutil.PromiseReject) {
go func() {
defer cancel()
defer func() {
if r := recover(); r != nil {
if err, ok := r.(error); ok {
reject(fmt.Sprintf("wasmhttp: panic: %+v\n", err))
} else {
reject(fmt.Sprintf("wasmhttp: panic: %v\n", r))
}
}
}()
var req, err = jsReq.HTTPRequest()
if err != nil {
panic(err)
}
var res = whutil.NewResponseWriter()
fmt.Printf("serving %s\n", req.URL.String())
h.ServeHTTP(res, req)
resolve(res)
}()
})
return resPromise
})
js.Global().Get("wasmhttp").Call("registerHandler", os.Getenv("WASMHTTP_HANDLER_ID"), cb)
<-ctx.Done()
}