-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrouter.go
More file actions
686 lines (570 loc) · 21.1 KB
/
router.go
File metadata and controls
686 lines (570 loc) · 21.1 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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
package forge
import (
"time"
"github.com/xraph/forge/errors"
"github.com/xraph/forge/internal/router"
"github.com/xraph/forge/internal/shared"
)
// HTTPError represents an HTTP error for backward compatibility.
type HTTPError = errors.HTTPError
var (
NewHTTPError = errors.NewHTTPError
BadRequest = errors.BadRequest
Unauthorized = errors.Unauthorized
Forbidden = errors.Forbidden
NotFound = errors.NotFound
InternalError = errors.InternalError
)
// Router provides HTTP routing with multiple backend support.
type Router = router.Router
// RouteOption configures a route.
type RouteOption = router.RouteOption
// GroupOption configures a route group.
type GroupOption = router.GroupOption
// Handler is a forge handler function.
type Handler = router.Handler
// Middleware wraps HTTP handlers.
type Middleware = router.Middleware
// RouteConfig holds route configuration.
type RouteConfig = router.RouteConfig
// GroupConfig holds route group configuration.
type GroupConfig = router.GroupConfig
// RouteInfo provides route information for inspection.
type RouteInfo = router.RouteInfo
// RouteExtension represents a route-level extension (e.g., OpenAPI, custom validation)
// Note: This is different from app-level Extension which manages app components.
type RouteExtension = router.RouteExtension
// NewRouter creates a new router with options.
func NewRouter(opts ...RouterOption) Router {
return router.NewRouter(opts...)
}
// GetRouter resolves the router from the container
// Returns the router instance and an error if resolution fails.
func GetRouter(c Container) (Router, error) {
return router.GetRouter(c)
}
// RouterOption configures the router.
type RouterOption = router.RouterOption
// RouterAdapter wraps a routing backend.
type RouterAdapter = router.RouterAdapter
// ErrorHandler handles errors from handlers.
type ErrorHandler = shared.ErrorHandler
// NewDefaultErrorHandler creates a default error handler.
func NewDefaultErrorHandler(l Logger) ErrorHandler {
return shared.NewDefaultErrorHandler(l)
}
// WithName sets the route name.
func WithName(name string) RouteOption {
return router.WithName(name)
}
func WithSummary(summary string) RouteOption {
return router.WithSummary(summary)
}
func WithDescription(desc string) RouteOption {
return router.WithDescription(desc)
}
func WithTags(tags ...string) RouteOption {
return router.WithTags(tags...)
}
func WithMiddleware(mw ...Middleware) RouteOption {
return router.WithMiddleware(mw...)
}
func WithTimeout(d time.Duration) RouteOption {
return router.WithTimeout(d)
}
func WithMetadata(key string, value any) RouteOption {
return router.WithMetadata(key, value)
}
func WithExtension(name string, ext Extension) RouteOption {
return router.WithExtension(name, ext)
}
func WithOperationID(id string) RouteOption {
return router.WithOperationID(id)
}
func WithDeprecated() RouteOption {
return router.WithDeprecated()
}
// WithSensitiveFieldCleaning enables cleaning of sensitive fields in responses.
// Fields marked with the `sensitive` tag will be processed before JSON serialization:
// - sensitive:"true" -> set to zero value (empty string, 0, nil)
// - sensitive:"redact" -> set to "[REDACTED]"
// - sensitive:"mask:***" -> set to custom mask "***"
//
// Example:
//
// type UserResponse struct {
// ID string `json:"id"`
// Password string `json:"password" sensitive:"true"`
// APIKey string `json:"api_key" sensitive:"redact"`
// Token string `json:"token" sensitive:"mask:***"`
// }
//
// router.GET("/user", handler, forge.WithSensitiveFieldCleaning())
func WithSensitiveFieldCleaning() RouteOption {
return router.WithSensitiveFieldCleaning()
}
// WithMethod overrides the HTTP method for a route.
// Primarily used for SSE/WebSocket endpoints that default to GET.
//
// Example:
//
// // Default GET behavior
// router.SSE("/events", handler)
//
// // Override to POST
// router.SSE("/events", handler, forge.WithMethod(http.MethodPost))
//
// // POST SSE with request body
// router.EventStream("/stream", streamHandler,
// forge.WithMethod(http.MethodPost),
// forge.WithTags("streaming"),
// )
func WithMethod(method string) RouteOption {
return router.WithMethod(method)
}
// OpenAPI Schema Options
// WithRequestSchema sets the unified request schema for OpenAPI generation.
// This is the recommended approach that automatically classifies struct fields based on tags:
// - path:"paramName" - Path parameter
// - query:"paramName" - Query parameter
// - header:"HeaderName" - Header parameter
// - body:"" or json:"fieldName" - Request body field
//
// Example:
//
// type CreateUserRequest struct {
// TenantID string `path:"tenantId" description:"Tenant ID" format:"uuid"`
// DryRun bool `query:"dryRun" description:"Preview mode"`
// APIKey string `header:"X-API-Key" description:"API Key"`
// Name string `json:"name" body:"" description:"User name" minLength:"1"`
// Email string `json:"email" body:"" description:"Email" format:"email"`
// }
//
// If the struct has no path/query/header tags, it's treated as body-only for backward compatibility.
func WithRequestSchema(schemaOrType any) RouteOption {
return router.WithRequestSchema(schemaOrType)
}
// WithRequestBodySchema sets only the request body schema for OpenAPI generation.
// Use this for explicit body-only schemas when you need separate schemas for different parts.
func WithRequestBodySchema(schemaOrType any) RouteOption {
return router.WithRequestBodySchema(schemaOrType)
}
// WithResponseSchema sets a response schema for OpenAPI generation.
func WithResponseSchema(statusCode int, description string, schemaOrType any) RouteOption {
return router.WithResponseSchema(statusCode, description, schemaOrType)
}
// WithQuerySchema sets the query parameters schema for OpenAPI generation.
func WithQuerySchema(schemaType any) RouteOption {
return router.WithQuerySchema(schemaType)
}
// WithHeaderSchema sets the header parameters schema for OpenAPI generation.
func WithHeaderSchema(schemaType any) RouteOption {
return router.WithHeaderSchema(schemaType)
}
// WithRequestContentTypes specifies the content types for request body.
func WithRequestContentTypes(types ...string) RouteOption {
return router.WithRequestContentTypes(types...)
}
// WithResponseContentTypes specifies the content types for response body.
func WithResponseContentTypes(types ...string) RouteOption {
return router.WithResponseContentTypes(types...)
}
// OpenAPI Advanced Features
// WithDiscriminator adds discriminator support for polymorphic schemas.
func WithDiscriminator(config DiscriminatorConfig) RouteOption {
return router.WithDiscriminator(config)
}
// WithRequestExample adds an example for the request body.
func WithRequestExample(name string, example any) RouteOption {
return router.WithRequestExample(name, example)
}
// WithResponseExample adds an example for a specific response status code.
func WithResponseExample(statusCode int, name string, example any) RouteOption {
return router.WithResponseExample(statusCode, name, example)
}
// WithSchemaRef adds a schema reference to components.
func WithSchemaRef(name string, schema any) RouteOption {
return router.WithSchemaRef(name, schema)
}
// OpenAPI Response Helpers
// WithPaginatedResponse creates a route option for paginated list responses.
func WithPaginatedResponse(itemType any, statusCode int) RouteOption {
return router.WithPaginatedResponse(itemType, statusCode)
}
// WithErrorResponses adds standard HTTP error responses to a route.
func WithErrorResponses() RouteOption {
return router.WithErrorResponses()
}
// WithStandardRESTResponses adds standard REST CRUD responses for a resource.
func WithStandardRESTResponses(resourceType any) RouteOption {
return router.WithStandardRESTResponses(resourceType)
}
// WithFileUploadResponse creates a response for file upload success.
func WithFileUploadResponse(statusCode int) RouteOption {
return router.WithFileUploadResponse(statusCode)
}
// WithNoContentResponse creates a 204 No Content response.
func WithNoContentResponse() RouteOption {
return router.WithNoContentResponse()
}
// WithCreatedResponse creates a 201 Created response.
func WithCreatedResponse(resourceType any) RouteOption {
return router.WithCreatedResponse(resourceType)
}
// WithAcceptedResponse creates a 202 Accepted response for async operations.
func WithAcceptedResponse() RouteOption {
return router.WithAcceptedResponse()
}
// WithListResponse creates a simple list response (array of items).
func WithListResponse(itemType any, statusCode int) RouteOption {
return router.WithListResponse(itemType, statusCode)
}
// WithBatchResponse creates a response for batch operations.
func WithBatchResponse(itemType any, statusCode int) RouteOption {
return router.WithBatchResponse(itemType, statusCode)
}
// WithValidationErrorResponse adds a 422 Unprocessable Entity response for validation errors.
func WithValidationErrorResponse() RouteOption {
return router.WithValidationErrorResponse()
}
// Validation Options
// WithValidation adds validation middleware to a route.
func WithValidation(enabled bool) RouteOption {
return router.WithValidation(enabled)
}
// WithStrictValidation enables strict validation (validates both request and response).
func WithStrictValidation() RouteOption {
return router.WithStrictValidation()
}
// Callback and Webhook Options
// WithCallback adds a callback definition to a route.
func WithCallback(config CallbackConfig) RouteOption {
return router.WithCallback(config)
}
// WithWebhook adds a webhook definition to the OpenAPI spec.
func WithWebhook(name string, operation *CallbackOperation) RouteOption {
return router.WithWebhook(name, operation)
}
// OpenAPI Type Exports
// DiscriminatorConfig defines discriminator for polymorphic types.
type DiscriminatorConfig = router.DiscriminatorConfig
// CallbackConfig defines a callback (webhook) for an operation.
type CallbackConfig = router.CallbackConfig
// CallbackOperation defines an operation that will be called back.
type CallbackOperation = router.CallbackOperation
// ValidationError represents a single field validation error.
type ValidationError = router.ValidationError
// ValidationErrors is a collection of validation errors.
//
//nolint:errname // Type alias to router.ValidationErrors
type ValidationErrors = router.ValidationErrors
// ResponseSchemaDef defines a response schema.
type ResponseSchemaDef = router.ResponseSchemaDef
// Callback and Webhook Helpers
// NewCallbackOperation creates a new callback operation.
func NewCallbackOperation(summary, description string) *CallbackOperation {
return router.NewCallbackOperation(summary, description)
}
// NewEventCallbackConfig creates a callback config for event notifications.
func NewEventCallbackConfig(callbackURLExpression string, eventSchema any) CallbackConfig {
return router.NewEventCallbackConfig(callbackURLExpression, eventSchema)
}
// NewStatusCallbackConfig creates a callback config for status updates.
func NewStatusCallbackConfig(callbackURLExpression string, statusSchema any) CallbackConfig {
return router.NewStatusCallbackConfig(callbackURLExpression, statusSchema)
}
// NewCompletionCallbackConfig creates a callback config for async operation completion.
func NewCompletionCallbackConfig(callbackURLExpression string, resultSchema any) CallbackConfig {
return router.NewCompletionCallbackConfig(callbackURLExpression, resultSchema)
}
// Validation Helpers
// NewValidationErrors creates a new ValidationErrors instance.
func NewValidationErrors() *ValidationErrors {
return router.NewValidationErrors()
}
// WithGroupMiddleware adds middleware to a route group.
func WithGroupMiddleware(mw ...Middleware) GroupOption {
return router.WithGroupMiddleware(mw...)
}
func WithGroupTags(tags ...string) GroupOption {
return router.WithGroupTags(tags...)
}
func WithGroupMetadata(key string, value any) GroupOption {
return router.WithGroupMetadata(key, value)
}
// WithGroupSchemaExclude excludes all routes in this group from schema generation
// (OpenAPI, AsyncAPI, and oRPC).
//
// This is useful for internal/debug/admin route groups that shouldn't appear
// in public API documentation.
//
// Example:
//
// // Create an internal admin group
// adminGroup := router.Group("/admin", forge.WithGroupSchemaExclude())
// adminGroup.GET("/users", listUsers)
// adminGroup.DELETE("/cache", flushCache)
// // All routes in this group are excluded from schemas
func WithGroupSchemaExclude() GroupOption {
return &groupSchemaExcludeOpt{}
}
type groupSchemaExcludeOpt struct{}
func (o *groupSchemaExcludeOpt) Apply(cfg *router.GroupConfig) {
if cfg.Metadata == nil {
cfg.Metadata = make(map[string]any)
}
cfg.Metadata["openapi.exclude"] = true
cfg.Metadata["asyncapi.exclude"] = true
cfg.Metadata["orpc.exclude"] = true
}
// WithAdapter sets the router adapter.
func WithAdapter(adapter RouterAdapter) RouterOption {
return router.WithAdapter(adapter)
}
func WithContainer(container Container) RouterOption {
return router.WithContainer(container)
}
func WithLogger(logger Logger) RouterOption {
return router.WithLogger(logger)
}
func WithErrorHandler(handler ErrorHandler) RouterOption {
return router.WithErrorHandler(handler)
}
func WithRecovery() RouterOption {
return router.WithRecovery()
}
// oRPC-specific route options for JSON-RPC method metadata
// WithORPCMethod sets a custom JSON-RPC method name for this route.
// By default, method names are generated from the HTTP method and path.
//
// Example:
//
// router.GET("/users/:id", getUserHandler,
// forge.WithORPCMethod("user.get"),
// )
func WithORPCMethod(methodName string) RouteOption {
return WithMetadata("orpc.method", methodName)
}
// WithORPCParams sets the params schema for OpenRPC schema generation.
// The schema should be a struct or map describing the expected parameters.
//
// Example:
//
// type UserGetParams struct {
// ID string `json:"id"`
// }
// router.GET("/users/:id", getUserHandler,
// forge.WithORPCParams(&orpc.ParamsSchema{
// Type: "object",
// Properties: map[string]*orpc.PropertySchema{
// "id": {Type: "string", Description: "User ID"},
// },
// Required: []string{"id"},
// }),
// )
func WithORPCParams(schema any) RouteOption {
return WithMetadata("orpc.params", schema)
}
// WithORPCResult sets the result schema for OpenRPC schema generation.
// The schema should be a struct or map describing the expected result.
//
// Example:
//
// router.GET("/users/:id", getUserHandler,
// forge.WithORPCResult(&orpc.ResultSchema{
// Type: "object",
// Description: "User details",
// }),
// )
func WithORPCResult(schema any) RouteOption {
return WithMetadata("orpc.result", schema)
}
// WithORPCExclude excludes this route from oRPC auto-exposure.
// Use this to prevent specific routes from being exposed as JSON-RPC methods.
//
// Example:
//
// router.GET("/internal/debug", debugHandler,
// forge.WithORPCExclude(),
// )
func WithORPCExclude() RouteOption {
return WithMetadata("orpc.exclude", true)
}
// WithOpenAPIExclude excludes this route from OpenAPI schema generation.
// Use this to prevent specific routes from appearing in OpenAPI documentation.
//
// Example:
//
// router.GET("/internal/health", healthHandler,
// forge.WithOpenAPIExclude(),
// )
func WithOpenAPIExclude() RouteOption {
return WithMetadata("openapi.exclude", true)
}
// WithAsyncAPIExclude excludes this route from AsyncAPI schema generation.
// Use this to prevent WebSocket/SSE routes from appearing in AsyncAPI documentation.
//
// Example:
//
// router.WebSocket("/internal/debug-stream", debugStreamHandler,
// forge.WithAsyncAPIExclude(),
// )
func WithAsyncAPIExclude() RouteOption {
return WithMetadata("asyncapi.exclude", true)
}
// WithSchemaExclude excludes this route from all schema generation (OpenAPI, AsyncAPI, oRPC).
// This is a convenience method that combines all exclusion options.
//
// Example:
//
// router.GET("/internal/debug", debugHandler,
// forge.WithSchemaExclude(),
// )
func WithSchemaExclude() RouteOption {
return &schemaExcludeOpt{}
}
type schemaExcludeOpt struct{}
func (o *schemaExcludeOpt) Apply(cfg *router.RouteConfig) {
if cfg.Metadata == nil {
cfg.Metadata = make(map[string]any)
}
cfg.Metadata["openapi.exclude"] = true
cfg.Metadata["asyncapi.exclude"] = true
cfg.Metadata["orpc.exclude"] = true
}
// WithExtensionExclusion checks if an extension implements InternalExtension
// and automatically excludes its routes from schema generation if needed.
//
// This is a helper function for extensions to use when registering routes.
//
// Example:
//
// func (e *DebugExtension) Start(ctx context.Context) error {
// router := e.app.Router()
// opts := forge.WithExtensionExclusion(e)
//
// router.GET("/debug/status", statusHandler, opts)
// router.GET("/debug/metrics", metricsHandler, opts)
// return nil
// }
func WithExtensionExclusion(ext Extension) RouteOption {
// Check if extension implements InternalExtension
if internal, ok := ext.(InternalExtension); ok && internal.ExcludeFromSchemas() {
return WithSchemaExclude()
}
// Return no-op option
return &noOpRouteOpt{}
}
// InternalExtension is re-exported from router package for convenience.
type InternalExtension = router.InternalExtension
type noOpRouteOpt struct{}
func (o *noOpRouteOpt) Apply(cfg *router.RouteConfig) {
// No-op
}
// ExtensionRoutes returns route options that automatically apply schema exclusion
// based on whether the extension implements InternalExtension.
//
// This is a convenience function for extensions registering multiple routes.
//
// Example:
//
// func (e *DebugExtension) Start(ctx context.Context) error {
// router := e.app.Router()
// opts := forge.ExtensionRoutes(e)
//
// router.GET("/debug/status", statusHandler, opts...)
// router.GET("/debug/metrics", metricsHandler, opts...)
// return nil
// }
func ExtensionRoutes(ext Extension, additionalOpts ...RouteOption) []RouteOption {
opts := []RouteOption{}
// Add exclusion if extension is internal
if internal, ok := ext.(InternalExtension); ok && internal.ExcludeFromSchemas() {
opts = append(opts, WithSchemaExclude())
}
// Add any additional options
opts = append(opts, additionalOpts...)
return opts
}
// WithORPCTags adds custom tags for OpenRPC schema organization.
// These tags are used in addition to the route's regular tags.
//
// Example:
//
// router.GET("/users/:id", getUserHandler,
// forge.WithORPCTags("users", "read"),
// )
func WithORPCTags(tags ...string) RouteOption {
return WithMetadata("orpc.tags", tags)
}
// WithORPCPrimaryResponse sets which response status code should be used as the primary
// oRPC result schema when multiple success responses (200, 201, etc.) are defined.
// This is useful when you have both 200 and 201 responses and want to explicitly choose one.
//
// By default, oRPC uses method-aware selection:
// - POST: Prefers 201, then 200
// - GET: Prefers 200
// - PUT/PATCH/DELETE: Prefers 200
//
// Example:
//
// router.POST("/users", createUserHandler,
// forge.WithResponseSchema(200, "Updated user", UserResponse{}),
// forge.WithResponseSchema(201, "Created user", UserResponse{}),
// forge.WithORPCPrimaryResponse(200), // Explicitly use 200
// )
func WithORPCPrimaryResponse(statusCode int) RouteOption {
return WithMetadata("orpc.primaryResponse", statusCode)
}
// Authentication route options
// WithAuth adds authentication to a route using one or more providers.
// Multiple providers create an OR condition - any one succeeding allows access.
//
// Example:
//
// router.GET("/protected", handler,
// forge.WithAuth("api-key", "jwt"),
// )
func WithAuth(providerNames ...string) RouteOption {
return router.WithAuth(providerNames...)
}
// WithRequiredAuth adds authentication with required scopes/permissions.
// The specified provider must succeed AND the auth context must have all required scopes.
//
// Example:
//
// router.POST("/admin/users", handler,
// forge.WithRequiredAuth("jwt", "write:users", "admin"),
// )
func WithRequiredAuth(providerName string, scopes ...string) RouteOption {
return router.WithRequiredAuth(providerName, scopes...)
}
// WithAuthAnd requires ALL specified providers to succeed (AND condition).
// This is useful for multi-factor authentication or combining auth methods.
//
// Example:
//
// router.GET("/high-security", handler,
// forge.WithAuthAnd("api-key", "mfa"),
// )
func WithAuthAnd(providerNames ...string) RouteOption {
return router.WithAuthAnd(providerNames...)
}
// Authentication group options
// WithGroupAuth adds authentication to all routes in a group.
// Multiple providers create an OR condition.
//
// Example:
//
// api := router.Group("/api", forge.WithGroupAuth("jwt"))
func WithGroupAuth(providerNames ...string) GroupOption {
return router.WithGroupAuth(providerNames...)
}
// WithGroupAuthAnd requires all providers to succeed for all routes in the group.
func WithGroupAuthAnd(providerNames ...string) GroupOption {
return router.WithGroupAuthAnd(providerNames...)
}
// WithGroupRequiredScopes sets required scopes for all routes in a group.
func WithGroupRequiredScopes(scopes ...string) GroupOption {
return router.WithGroupRequiredScopes(scopes...)
}