forked from yisar/labor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
serve.go
54 lines (42 loc) · 992 Bytes
/
serve.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package labor
import (
"fmt"
"net/http"
"strings"
"syscall/js"
)
func Serve(handler http.Handler) func() {
var h = handler
if h == nil {
h = http.DefaultServeMux
}
var prefix = js.Global().Get("labor").Get("path").String()
for strings.HasSuffix(prefix, "/") {
prefix = strings.TrimSuffix(prefix, "/")
}
if prefix != "" {
var mux = http.NewServeMux()
mux.Handle(prefix+"/", http.StripPrefix(prefix, h))
h = mux
}
var cb = js.FuncOf(func(_ js.Value, args []js.Value) interface{} {
var resPromise, resolve, reject = NewPromise()
go func() {
defer func() {
if r := recover(); r != nil {
if err, ok := r.(error); ok {
reject(fmt.Sprintf("labor: panic: %+v\n", err))
} else {
reject(fmt.Sprintf("labor: panic: %v\n", r))
}
}
}()
var res = NewResponseRecorder()
h.ServeHTTP(res, Request(args[0]))
resolve(res)
}()
return resPromise
})
js.Global().Get("labor").Call("setHandler", cb)
return cb.Release
}