-
-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathserve.go
86 lines (68 loc) · 1.5 KB
/
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package wasmhttp
import (
"context"
"fmt"
"net/http"
"strings"
"syscall/js"
"github.com/nlepage/go-wasm-http-server/v2/internal/safejs"
)
var (
wasmhttp = safejs.Safe(js.Global().Get("wasmhttp"))
)
// Serve serves HTTP requests using handler or http.DefaultServeMux if handler is nil.
func Serve(handler http.Handler) (func(), error) {
h := handler
if h == nil {
h = http.DefaultServeMux
}
prefix, err := wasmhttp.GetString("path")
if err != nil {
return nil, err
}
for strings.HasSuffix(prefix, "/") {
prefix = strings.TrimSuffix(prefix, "/")
}
if prefix != "" {
mux := http.NewServeMux()
mux.Handle(prefix+"/", http.StripPrefix(prefix, h))
h = mux
}
handlerValue, err := safejs.FuncOf(func(_ safejs.Value, args []safejs.Value) interface{} {
res, err := NewResponse()
if err != nil {
panic(err)
}
go func() {
ctx, cancel := context.WithCancel(res.Context())
defer func() {
cancel()
}()
defer func() {
if err := res.Close(); err != nil {
panic(err)
}
}()
defer func() {
if r := recover(); r != nil {
res.WriteError(fmt.Sprintf("%+v", r))
}
}()
req, err := Request(safejs.Unsafe(args[0]))
if err != nil {
res.WriteError(fmt.Sprintf("%+v", err))
return
}
req = req.WithContext(ctx)
h.ServeHTTP(res, req)
}()
return res.JSValue()
})
if err != nil {
return nil, err
}
if _, err = wasmhttp.Call("setHandler", handlerValue); err != nil {
return nil, err
}
return handlerValue.Release, nil
}