-
Notifications
You must be signed in to change notification settings - Fork 0
/
group.go
236 lines (201 loc) · 6.86 KB
/
group.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
package medium
import (
"context"
"net/http"
"regexp"
)
type dispatchable[T any] interface {
dispatch(r *RootRequest) (bool, *RouteData, func(context.Context, *Request[T]) Response)
}
var _ dispatchable[NoData] = (*RouteGroup[NoData, NoData])(nil)
// registerable represents a type that can be registered on a router or a group
// to create subgroups/subrouters.
type registerable[Data any] interface {
register(dispatchable[Data])
prefix() string
}
// RouteGroup represents a collection of routes that share a common set of
// Around/Before/After callbacks and Action type (T)
type RouteGroup[ParentData any, Data any] struct {
routes []*Route[Data]
dataCreator func(ctx context.Context, r *Request[ParentData]) (context.Context, Data)
subgroups []dispatchable[Data]
befores []BeforeFunc[Data]
routePrefix string
}
// SubRouter creates a new grouping of routes that will be routed to in addition
// to the routes defined on the primery router. These routes will be prefixed
// using the given prefix.
//
// Subrouters provide their own action creator, so common behavior can be
// grouped via a custom action.
//
// Diagram of what the "inheritance" chain can look like:
//
// router[GlobalAction]
// |
// |_Group[GlobalAction, LoggedInAction]
// |
// |-Group[LoggedInAction, Teams]
// |
// |-Group[LoggedInAction, Settings]
// |
// |-Group[LoggedInAction, Admin]
// |
// |_ Group[Admin, SuperAdmin]
func SubRouter[
ParentData any,
Data any,
Parent registerable[ParentData],
](
parent Parent,
prefix string,
creator func(r *Request[ParentData]) Data,
) *RouteGroup[ParentData, Data] {
return SubRouterWithContext(parent, prefix, func(ctx context.Context, r *Request[ParentData]) (context.Context, Data) {
return ctx, creator(r)
})
}
// SubRouterWithContext has the same behavior as SubRouter but passes the
// context to the data creator and
func SubRouterWithContext[
ParentData any,
Data any,
Parent registerable[ParentData],
](
parent Parent,
prefix string,
creator func(ctx context.Context, r *Request[ParentData]) (context.Context, Data),
) *RouteGroup[ParentData, Data] {
group := GroupWithContext(parent, creator)
group.routePrefix = parent.prefix() + prefix
return group
}
// NewGroup creates a new route Group that can be used to group around
// filters and other common behavior.
//
// An action creator function is passed to the NewGroup, so that it can reference
// fields from the parent action type.
func Group[
ParentData any,
Data any,
Parent registerable[ParentData],
](
parent Parent,
creator func(r *Request[ParentData]) Data,
) *RouteGroup[ParentData, Data] {
group := &RouteGroup[ParentData, Data]{
routes: make([]*Route[Data], 0),
dataCreator: func(ctx context.Context, r *Request[ParentData]) (context.Context, Data) {
return ctx, creator(r)
},
}
group.routePrefix = parent.prefix()
parent.register(group)
return group
}
// GroupWithContext has the same behavior as Group but passes the
// context to the data creator and requires a context to be returned.
func GroupWithContext[
ParentData any,
Data any,
Parent registerable[ParentData],
](
parent Parent,
creator func(context.Context, *Request[ParentData]) (context.Context, Data),
) *RouteGroup[ParentData, Data] {
group := &RouteGroup[ParentData, Data]{routes: make([]*Route[Data], 0), dataCreator: creator}
group.routePrefix = parent.prefix()
parent.register(group)
return group
}
// Match defines a new Route that responds to requests that match the given
// method and path.
func (g *RouteGroup[ParentData, Data]) Match(method string, path string, handler HandlerFunc[Data]) {
if path == "/" {
path = g.routePrefix
} else {
path = joinPath(g.routePrefix, path)
}
if path == "" {
path = "/"
}
g.routes = append(g.routes, newRoute(method, path, handler))
}
// Defines a new Route that responds to GET requests.
func (g *RouteGroup[ParentData, Data]) Get(path string, handler HandlerFunc[Data]) {
g.Match(http.MethodGet, path, handler)
}
// Defines a new Route that responds to POST requests.
func (g *RouteGroup[ParentData, Data]) Post(path string, handler HandlerFunc[Data]) {
g.Match(http.MethodPost, path, handler)
}
// Defines a new Route that responds to PUT requests.
func (t *RouteGroup[ParentData, Data]) Put(path string, handler HandlerFunc[Data]) {
t.Match(http.MethodPut, path, handler)
}
// Defines a new Route that responds to PATCH requests.
func (g *RouteGroup[ParentData, Data]) Patch(path string, handler HandlerFunc[Data]) {
g.Match(http.MethodPatch, path, handler)
}
// Defines a new Route that responds to DELETE requests.
func (g *RouteGroup[ParentData, Data]) Delete(path string, handler HandlerFunc[Data]) {
g.Match(http.MethodDelete, path, handler)
}
// Implements Dispatchable so groups can be registered on routers
func (g *RouteGroup[ParentData, Data]) dispatch(rootRequest *RootRequest) (bool, *RouteData, func(context.Context, *Request[ParentData]) Response) {
handler, routeData := g.routeFor(rootRequest)
if handler == nil {
return false, nil, nil
}
return true, routeData, func(ctx context.Context, req *Request[ParentData]) Response {
ctx, data := g.dataCreator(ctx, req)
newReq := NewRequest(rootRequest.originalRequest, data, routeData)
routeHandler := func(ctx context.Context, req *Request[Data]) Response { return handler(ctx, req) }
for i := len(g.befores) - 1; i >= 0; i-- {
currentHandler := routeHandler
before := g.befores[i]
routeHandler = func(ctx context.Context, req *Request[Data]) Response {
return before(ctx, req, func(ctx context.Context) Response {
return currentHandler(ctx, req)
})
}
}
return routeHandler(ctx, newReq)
}
}
func (g *RouteGroup[ParentData, Data]) routeFor(req *RootRequest) (HandlerFunc[Data], *RouteData) {
for _, route := range g.routes {
if ok, params := route.IsMatch(req); ok {
return route.handler, &RouteData{Params: params, HandlerPath: route.Raw}
}
}
for _, group := range g.subgroups {
if ok, routeData, handler := group.dispatch(req); ok {
return func(ctx context.Context, req *Request[Data]) Response {
return handler(ctx, req)
}, routeData
}
}
return nil, nil
}
// register implements the registerable interface and allows subgroups to be
// registered and routed to.
func (g *RouteGroup[ParentData, Data]) register(subgroup dispatchable[Data]) {
g.subgroups = append(g.subgroups, subgroup)
}
// prefix implements the registerable interface and allows subgroups to register
// routes with the correct path.
func (g *RouteGroup[ParentData, Data]) prefix() string {
return g.routePrefix
}
var trailingSlash = regexp.MustCompile("/+$")
var leadingSlash = regexp.MustCompile("^/+")
func joinPath(left string, right string) string {
left = trailingSlash.ReplaceAllString(left, "")
right = leadingSlash.ReplaceAllString(right, "")
return left + "/" + right
}
func (r *RouteGroup[ParentData, Data]) Before(before BeforeFunc[Data]) {
r.befores = append(r.befores, before)
}