Repository navigation
Expand file tree
/
Copy pathgroup.go
More file actions
361 lines (331 loc) · 11.9 KB
/
Copy pathgroup.go
File metadata and controls
361 lines (331 loc) · 11.9 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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
/*
* MIT License
*
* Copyright (c) 2025 Jonas Kaninda
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package okapi
import "net/http"
type Group struct {
// Prefix is the base path for all routes in this group.
Prefix string
// Tags is an optional tag for the group, used for documentation purposes.
Tags []string
tagInfos []GroupTag
disabled bool
bearerAuth bool
basicAuth bool
deprecated bool
middlewares []Middleware
okapi *Okapi
security []map[string][]string
}
// GroupTag describes an OpenAPI tag with a human-readable description.
// When attached to a Group via WithTagInfo, the tag is emitted at the
// root of the OpenAPI specification.
type GroupTag struct {
// Name is the tag name (matches what appears on Operation.Tags).
Name string
// Description is the human-readable description shown in the API docs.
Description string
// ExternalDocs optionally links to additional documentation for this tag.
ExternalDocs *ExternalDocs
}
// newGroup creates a new route group with the specified base path, Okapi reference,
// and optional middlewares.
func newGroup(basePath string, disabled bool, okapi *Okapi, middlewares ...Middleware) *Group {
mws := append([]Middleware{}, middlewares...)
return &Group{
Prefix: basePath,
middlewares: mws,
okapi: okapi,
disabled: disabled,
}
}
func NewGroup(basePath string, okapi *Okapi, middlewares ...Middleware) *Group {
if okapi == nil {
panic("okapi instance cannot be nil")
}
if basePath == "" {
panic("Prefix cannot be empty")
}
return newGroup(basePath, false, okapi, middlewares...)
}
// Disable marks the Group as disabled, causing all routes within it to return 404 Not Found.
// Returns the Group to allow method chaining.
func (g *Group) Disable() *Group {
g.disabled = true
return g
}
// Enable marks the Group as enabled, allowing all routes within it to handle requests normally.
// Returns the Group to allow method chaining.
func (g *Group) Enable() *Group {
g.disabled = false
return g
}
// setDisabled sets the unregistered state of the Group.
// When unregistered is true, all routes in the group return 404 Not Found.
// Returns the Group to allow method chaining.
func (g *Group) setDisabled(disabled bool) *Group {
g.disabled = disabled
return g
}
// WithBearerAuth marks the Group as requiring Bearer authentication for its routes.
// Returns the Group to allow method chaining.
func (g *Group) WithBearerAuth() *Group {
g.bearerAuth = true
return g
}
func (g *Group) WithBasicAuth() *Group {
g.basicAuth = true
return g
}
// WithTags sets the tags for the Group, which can be used for documentation purposes.
func (g *Group) WithTags(tags []string) *Group {
g.Tags = tags
return g
}
// WithTagInfo attaches one or more tag descriptions to the Group.
func (g *Group) WithTagInfo(tags ...GroupTag) *Group {
for _, t := range tags {
if t.Name == "" {
continue
}
g.tagInfos = append(g.tagInfos, t)
g.Tags = append(g.Tags, t.Name)
}
return g
}
// Deprecated marks the Group as deprecated for its routes.
// Returns the Group to allow method chaining.
func (g *Group) Deprecated() *Group {
g.deprecated = true
return g
}
// WithSecurity sets the security requirements for the Group's routes.
func (g *Group) WithSecurity(security []map[string][]string) *Group {
g.security = security
return g
}
// Okapi returns the parent Okapi instance associated with this group.
func (g *Group) Okapi() *Okapi {
return g.okapi
}
// Use adds one or more middlewares to the group's middleware chain.
// These middlewares will be executed in the order they are added,
// before the route handler for all routes within this group.
// Middlewares are inherited by any subgroups created from this group.
func (g *Group) Use(m ...Middleware) {
if len(m) == 0 {
return
}
g.middlewares = append(g.middlewares, m...)
}
// add is an internal method that handles route registration with the combined
// middlewares from both the group and parent Okapi instance.
func (g *Group) add(method, path string, h HandlerFunc, opts ...RouteOption) *Route {
if g.okapi == nil {
panic("okapi instance is nil, cannot register route")
}
fullPath := joinPaths(g.Prefix, path)
// Prepend group middleware before any route-level middleware
if len(g.middlewares) > 0 {
groupMW := make([]Middleware, len(g.middlewares))
copy(groupMW, g.middlewares)
opts = append([]RouteOption{UseMiddleware(groupMW...)}, opts...)
}
// Register the route with the joined base path and route path
route := g.okapi.addRoute(method, fullPath, g.Tags, h, opts...)
// Use group prefix as fallback
if len(route.tags) == 0 {
route.tags = []string{g.Prefix}
}
route.tagInfos = append(route.tagInfos, g.tagInfos...)
return route.setDisabled(g.disabled)
}
// handle is a helper method that delegates to add with the given HTTP method.
func (g *Group) handle(method, path string, h HandlerFunc, opts ...RouteOption) *Route {
if g.bearerAuth {
opts = append(opts, DocBearerAuth())
}
if g.basicAuth {
opts = append(opts, DocBasicAuth())
}
if g.deprecated {
opts = append(opts, DocDeprecated())
}
if len(g.security) > 0 {
opts = append(opts, withSecurity(g.security))
}
return g.add(method, path, h, opts...)
}
// Get registers a GET route within the group with the given path and handler.
func (g *Group) Get(path string, h HandlerFunc, opts ...RouteOption) *Route {
return g.handle(methodGet, path, h, opts...)
}
// Post registers a POST route within the group with the given path and handler.
func (g *Group) Post(path string, h HandlerFunc, opts ...RouteOption) *Route {
return g.handle(methodPost, path, h, opts...)
}
// Put registers a PUT route within the group with the given path and handler.
func (g *Group) Put(path string, h HandlerFunc, opts ...RouteOption) *Route {
return g.handle(methodPut, path, h, opts...)
}
// Delete registers a DELETE route within the group with the given path and handler.
func (g *Group) Delete(path string, h HandlerFunc, opts ...RouteOption) *Route {
return g.handle(methodDelete, path, h, opts...)
}
// Patch registers a PATCH route within the group with the given path and handler.
func (g *Group) Patch(path string, h HandlerFunc, opts ...RouteOption) *Route {
return g.handle(methodPatch, path, h, opts...)
}
// Options registers an OPTIONS route within the group with the given path and handler.
func (g *Group) Options(path string, h HandlerFunc, opts ...RouteOption) *Route {
return g.handle(methodOptions, path, h, opts...)
}
// Head registers a HEAD route within the group with the given path and handler.
func (g *Group) Head(path string, h HandlerFunc, opts ...RouteOption) *Route {
return g.handle(methodHead, path, h, opts...)
}
// Group creates a nested subgroup with an additional path segment and optional middlewares.
// The new group inherits all middlewares from its parent group.
func (g *Group) Group(path string, middlewares ...Middleware) *Group {
return newGroup(
// Combine paths
joinPaths(g.Prefix, path),
g.disabled,
// Share the same Okapi instance
g.okapi,
// Combine middlewares
append(g.middlewares, middlewares...)...)
}
// HandleStd registers a standard http.HandlerFunc and wraps it with the group's middleware chain.
func (g *Group) HandleStd(method, path string, h func(http.ResponseWriter, *http.Request), opts ...RouteOption) {
// Convert standard handler to HandlerFunc
converted := func(c *Context) error {
h(c.response, c.request)
return nil
}
// Prepend group middleware
if len(g.middlewares) > 0 {
groupMW := make([]Middleware, len(g.middlewares))
copy(groupMW, g.middlewares)
opts = append([]RouteOption{UseMiddleware(groupMW...)}, opts...)
}
tags := g.Tags
if len(tags) == 0 {
tags = []string{g.Prefix}
}
// Register route
route := g.okapi.addRoute(method, joinPaths(g.Prefix, path), tags, converted, opts...)
route.tagInfos = append(route.tagInfos, g.tagInfos...)
route.setDisabled(g.disabled)
}
// HandleHTTP registers a standard http.Handler and wraps it with the group's middleware chain.
func (g *Group) HandleHTTP(method, path string, h http.Handler, opts ...RouteOption) {
// Convert standard handler to HandlerFunc
converted := g.okapi.wrapHTTPHandler(h)
// Prepend group middleware
if len(g.middlewares) > 0 {
groupMW := make([]Middleware, len(g.middlewares))
copy(groupMW, g.middlewares)
opts = append([]RouteOption{UseMiddleware(groupMW...)}, opts...)
}
tags := g.Tags
if len(tags) == 0 {
tags = []string{g.Prefix}
}
// Register route
route := g.okapi.addRoute(method, joinPaths(g.Prefix, path), tags, converted, opts...)
route.tagInfos = append(route.tagInfos, g.tagInfos...)
route.setDisabled(g.disabled)
}
// UseMiddleware registers a standard HTTP middleware function and integrates
// it into Okapi's middleware chain.
//
// This enables compatibility with existing middleware libraries that use the
// func(http.Handler) http.Handler pattern.
func (g *Group) UseMiddleware(mw func(http.Handler) http.Handler) {
g.Use(func(c *Context) error {
// Convert the rest of the chain into an http.Handler
next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Continue the Okapi middleware chain
c.request = r
if err := c.Next(); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
})
// Apply standard middleware and serve
wrapped := mw(next)
wrapped.ServeHTTP(c.response, c.request)
return nil
})
}
// Register registers a slice of RouteDefinition with the group.
// It ensures that each route is associated with the group and its Okapi instance.
// If a route's Group field is nil, it assigns the current group to it.
// If the route's Group's Okapi reference is nil, it assigns the group's Okapi instance to it.
// This method is useful for bulk registering routes defined in a controller or similar structure.
//
// Example:
//
// routes := []okapi.RouteDefinition{
// {
// Method: "GET",
// Path: "/example",
// Handler: exampleHandler,
// Options: []okapi.RouteOption{
// okapi.DocSummary("Example GET request"),
// },
// },
// {
// Method: "POST",
// Path: "/example",
// Handler: exampleHandler,
// Options: []okapi.RouteOption{
// okapi.DocSummary("Example POST request"),
// },
// },
// }
// // Create a new Okapi instance
// app := okapi.New()
//
// api:= app.Group("/api")
//
// api.Register(routes...)
func (g *Group) Register(routes ...RouteDefinition) {
for _, r := range routes {
if r.Group == nil {
r.Group = g
} else if r.Group.okapi == nil {
r.Group.okapi = g.okapi
}
for _, mid := range r.Middlewares {
r.Options = append(r.Options, UseMiddleware(mid))
}
route := g.okapi.addRoute(r.Method, joinPaths(g.Prefix, r.Path), r.Group.Tags, r.Handler, r.Options...)
// Use group prefix as fallback
if len(route.tags) == 0 {
route.tags = []string{g.Prefix}
}
route.tagInfos = append(route.tagInfos, r.Group.tagInfos...)
route.setDisabled(g.disabled)
}
}