-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgroup.go
More file actions
241 lines (220 loc) · 7.82 KB
/
group.go
File metadata and controls
241 lines (220 loc) · 7.82 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
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
237
238
239
240
241
// Copyright 2025 The Rivaas Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package app
import (
"fmt"
"net/http"
"strings"
"rivaas.dev/router"
"rivaas.dev/router/route"
)
// Group represents a route group that allows organizing related routes
// under a common path prefix with shared middleware.
// It enables hierarchical organization of API endpoints and middleware application.
//
// Groups created from App support app.HandlerFunc (with app.Context),
// providing access to binding and validation features.
//
// Example:
//
// api := app.Group("/api/v1", AuthMiddleware())
// api.GET("/users", handler) // handler receives *app.Context
// api.POST("/users", handler) // handler receives *app.Context
type Group struct {
app *App
router *route.Group
prefix string // Track prefix for building full paths
middleware []HandlerFunc // Group-specific middleware
}
// Use adds middleware to the group that will be executed for all routes in this group.
// Middleware is executed after the router's global middleware but before the
// route-specific handlers.
//
// Use panics if any middleware is nil because it is called after construction, where a nil
// middleware is a programming error. For construction-time middleware, use [WithMiddleware].
//
// Example:
//
// api := app.Group("/api")
// api.Use(AuthMiddleware(), LoggingMiddleware())
// api.GET("/users", getUsersHandler) // Will execute auth + logging + handler
func (g *Group) Use(middleware ...HandlerFunc) {
for i, m := range middleware {
if m == nil {
panic(fmt.Sprintf("app: group middleware at index %d cannot be nil", i))
}
}
g.middleware = append(g.middleware, middleware...)
}
// Group creates a nested route group under the current group.
// It combines the parent's prefix with the provided prefix and
// inherits middleware from the parent group.
//
// Group panics if any middleware is nil because it is called after construction, where a nil
// middleware is a programming error. For construction-time middleware, use [WithMiddleware].
//
// Example:
//
// api := app.Group("/api")
// v1 := api.Group("/v1") // Creates /api/v1 prefix
// v1.GET("/users", handler) // Matches /api/v1/users
func (g *Group) Group(prefix string, middleware ...HandlerFunc) *Group {
for i, m := range middleware {
if m == nil {
panic(fmt.Sprintf("app: group middleware at index %d cannot be nil", i))
}
}
// Build full prefix for nested group
fullPrefix := g.buildFullPath(prefix)
// Combine parent middleware with new middleware
allMiddleware := make([]HandlerFunc, 0, len(g.middleware)+len(middleware))
allMiddleware = append(allMiddleware, g.middleware...)
allMiddleware = append(allMiddleware, middleware...)
// Create router group without middleware (we handle it at route registration)
routerGroup := g.router.Group(prefix)
return &Group{
app: g.app,
router: routerGroup,
prefix: fullPrefix,
middleware: allMiddleware,
}
}
// addRoute adds a route to the group by combining the group's middleware with handlers.
// It returns the underlying route.Route for constraint configuration.
// It delegates to the app's registerRouteWithTarget with a routeTarget for this group.
func (g *Group) addRoute(method, path string, handler HandlerFunc, opts ...RouteOption) *route.Route {
target := routeTarget{
prefixMiddleware: g.middleware,
getFullPath: g.buildFullPath,
version: "",
register: func(method, pathForRouter, _ string, handlers []router.HandlerFunc) *route.Route {
// route.Group expects []route.Handler (Handler = any)
routeHandlers := make([]route.Handler, 0, len(handlers))
for _, h := range handlers {
routeHandlers = append(routeHandlers, h)
}
return g.router.Handle(method, pathForRouter, routeHandlers...)
},
}
return g.app.registerRouteWithTarget(target, method, path, handler, opts...)
}
// GET adds a GET route to the group with the group's prefix.
//
// Example:
//
// api := app.Group("/api/v1")
// api.GET("/users", handler)
// api.GET("/users/:id", getUser,
// app.WithDoc(openapi.WithSummary("Get user")),
// )
func (g *Group) GET(path string, handler HandlerFunc, opts ...RouteOption) *route.Route {
return g.addRoute(http.MethodGet, path, handler, opts...)
}
// POST adds a POST route to the group with the group's prefix.
//
// Example:
//
// api := app.Group("/api/v1")
// api.POST("/users", createUser,
// app.WithDoc(
// openapi.WithSummary("Create user"),
// openapi.WithRequest(CreateUserRequest{}),
// ),
// )
func (g *Group) POST(path string, handler HandlerFunc, opts ...RouteOption) *route.Route {
return g.addRoute(http.MethodPost, path, handler, opts...)
}
// PUT adds a PUT route to the group with the group's prefix.
//
// Example:
//
// api := app.Group("/api/v1")
// api.PUT("/users/:id", updateUser)
func (g *Group) PUT(path string, handler HandlerFunc, opts ...RouteOption) *route.Route {
return g.addRoute(http.MethodPut, path, handler, opts...)
}
// DELETE adds a DELETE route to the group with the group's prefix.
//
// Example:
//
// api := app.Group("/api/v1")
// api.DELETE("/users/:id", deleteUser)
func (g *Group) DELETE(path string, handler HandlerFunc, opts ...RouteOption) *route.Route {
return g.addRoute(http.MethodDelete, path, handler, opts...)
}
// PATCH adds a PATCH route to the group with the group's prefix.
//
// Example:
//
// api := app.Group("/api/v1")
// api.PATCH("/users/:id", patchUser)
func (g *Group) PATCH(path string, handler HandlerFunc, opts ...RouteOption) *route.Route {
return g.addRoute(http.MethodPatch, path, handler, opts...)
}
// HEAD adds a HEAD route to the group with the group's prefix.
//
// Example:
//
// api := app.Group("/api/v1")
// api.HEAD("/users/:id", handler)
func (g *Group) HEAD(path string, handler HandlerFunc, opts ...RouteOption) *route.Route {
return g.addRoute(http.MethodHead, path, handler, opts...)
}
// OPTIONS adds an OPTIONS route to the group with the group's prefix.
//
// Example:
//
// api := app.Group("/api/v1")
// api.OPTIONS("/users", handler)
func (g *Group) OPTIONS(path string, handler HandlerFunc, opts ...RouteOption) *route.Route {
return g.addRoute(http.MethodOptions, path, handler, opts...)
}
// Any registers a route that matches all HTTP methods.
// It is useful for catch-all endpoints like health checks or proxies.
//
// It registers 7 separate routes internally (GET, POST, PUT, DELETE,
// PATCH, HEAD, OPTIONS). For endpoints that only need specific methods,
// use individual method registrations (GET, POST, etc.).
//
// Returns the GET route (most common for docs/constraints).
//
// Example:
//
// api := app.Group("/api/v1")
// api.Any("/health", healthCheckHandler)
func (g *Group) Any(path string, handler HandlerFunc, opts ...RouteOption) *route.Route {
rt := g.GET(path, handler, opts...)
g.POST(path, handler, opts...)
g.PUT(path, handler, opts...)
g.DELETE(path, handler, opts...)
g.PATCH(path, handler, opts...)
g.HEAD(path, handler, opts...)
g.OPTIONS(path, handler, opts...)
return rt
}
// buildFullPath builds the full path by combining group prefix with the route path.
func (g *Group) buildFullPath(path string) string {
if len(g.prefix) == 0 {
return path
}
if len(path) == 0 {
return g.prefix
}
// Both non-empty: concatenate
var sb strings.Builder
sb.Grow(len(g.prefix) + len(path))
_, _ = sb.WriteString(g.prefix)
_, _ = sb.WriteString(path)
return sb.String()
}