-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandler.go
More file actions
94 lines (75 loc) · 2.38 KB
/
handler.go
File metadata and controls
94 lines (75 loc) · 2.38 KB
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
87
88
89
90
91
92
93
94
package wazemmes
import (
"context"
"errors"
"net/http"
pool "github.com/jolestar/go-commons-pool/v2"
"go.uber.org/zap"
)
type HandlerFunc func(http.ResponseWriter, *http.Request) error
func (f HandlerFunc) ServeHTTP(w http.ResponseWriter, r *http.Request) error {
return f(w, r)
}
type Handler interface {
ServeHTTP(http.ResponseWriter, *http.Request) error
}
type WasmMiddleware func(http.ResponseWriter, *http.Request, http.Handler) error
type WasmHandler struct {
Configuration configuration
pool *pool.ObjectPool
logger *zap.Logger
}
func NewWasmHandlerInstance(handler func(ctx context.Context, next Handler) Handler, poolConfiguration map[string]interface{}, logger *zap.Logger) (*WasmHandler, error) {
return &WasmHandler{
pool: newPoolConfiguration(handler, poolConfiguration),
logger: logger,
}, nil
}
func NewWasmHandler(modulepath, builder string, moduleConfig any, poolConfiguration map[string]interface{}, logger *zap.Logger) (*WasmHandler, error) {
switch builder {
case "js", "javascript", "asc", "assemblyscript":
return NewWasmHandlerJS(modulepath, moduleConfig, poolConfiguration, logger)
case "php":
return NewWasmHandlerPHP(modulepath, moduleConfig, poolConfiguration, logger)
}
return NewWasmHandlerGo(modulepath, moduleConfig, poolConfiguration, logger)
}
func (w *WasmHandler) ServeHTTP(rw http.ResponseWriter, rq *http.Request, next Handler) error {
value, err := w.pool.BorrowObject(rq.Context())
defer func() {
_ = w.pool.ReturnObject(rq.Context(), value)
}()
if err != nil {
return err
}
handler, ok := value.(func(ctx context.Context, next Handler) Handler)
if !ok {
return errors.New("impossible to cast the borrowed object into a WASM HTTP handler")
}
result := handler(rq.Context(), next)
if result != nil {
err = result.ServeHTTP(rw, rq)
}
if err != nil {
return err
}
if next != nil {
return next.ServeHTTP(rw, rq)
}
return nil
}
func BuildMiddlewareChain(logger *zap.Logger, chain []*WasmHandler) Handler {
if len(chain) > 0 {
nextMw := chain[0]
return HandlerFunc(func(rw http.ResponseWriter, req *http.Request) error {
err := nextMw.ServeHTTP(rw, req, BuildMiddlewareChain(logger, chain[1:]))
if err != nil {
logger.Sugar().Errorf("error in WASM middleware: %#v", err)
}
return err
})
}
return HandlerFunc(func(rw http.ResponseWriter, req *http.Request) error {
return nil
})
}