-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathnew.go
91 lines (79 loc) · 2.45 KB
/
new.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
87
88
89
90
91
package torque
import (
"fmt"
"net/http"
)
func New[T ViewModel](ctl Controller) (Handler, error) {
var (
// vm is the zero value of the generic constraint that
// can be used in type assertions
vm ViewModel = new(T)
err error
)
h := createHandlerImpl[T]()
h.ctl = ctl
err = assertImplementations(h, ctl, vm)
if err != nil {
return nil, fmt.Errorf("failed to assert Controller interface: %w", err)
}
for _, plugin := range h.plugins {
err = plugin.Install(h)(ctl, vm)
if err != nil {
return nil, fmt.Errorf("failed to install Plugin %T: %w", plugin, err)
}
}
return h, nil
}
func MustNew[T ViewModel](ctl Controller) Handler {
h, err := New[T](ctl)
if err != nil {
panic(err)
}
return h
}
// NewV takes a vanilla http.Handler and wraps it into a torque.Handler.
//
// This allows it to be rendered to an outlet when used within a RouterProvider.
//
// It also enables parts of the Controller API including PluginProvider,
// GuardProvider and PanicBoundary. These interfaces can be implemented
// on the given http.Handler to provide additional functionality.
func NewV(handler http.Handler) (Handler, error) {
h := createHandlerImpl[any]()
h.handler = handler
// If the passed handler is actually an http.HandlerFunc it can't possiblly
// implement any of the torque Controller interfaces.
if _, ok := handler.(http.HandlerFunc); !ok {
err := assertImplementations(h, handler, new(any))
if err != nil {
return nil, fmt.Errorf("failed to assert interfaces: %w", err)
}
if err := checkInvalidImplementations(h, handler); err != nil {
return nil, fmt.Errorf("cannot mix ServeHTTP method with torque interface: %w", err)
}
}
return h, nil
}
func MustNewV(handler http.Handler) Handler {
h, err := NewV(handler)
if err != nil {
panic(err)
}
return h
}
func checkInvalidImplementations(h *handlerImpl[any], src interface{}) error {
if _, ok := src.(http.Handler); ok {
if h.loader != nil {
return fmt.Errorf("Loader interface not supported on type %T", src)
} else if h.action != nil {
return fmt.Errorf("Action interface not supported on type %T", src)
} else if h.rendererT != nil || h.rendererVM != nil {
return fmt.Errorf("Renderer interface not supported on type %T", src)
} else if h.errorBoundary != nil {
return fmt.Errorf("ErrorBoundary interface not supported on type %T", src)
} else if h.router != nil {
return fmt.Errorf("Router interface not supported on type %T", src)
}
}
return nil
}