Documentation
¶
Index ¶
- Constants
- Variables
- func ConvertPathToOpenAPIFormat(path string) string
- func FormatValidationError(err error) (int, []byte)
- func GetTypeName(t reflect.Type) string
- func ValidateQueryParams(r *http.Request, schemaType any) error
- func ValidateRequestBody(r *http.Request, schema *Schema) error
- type AsyncAPIChannel
- type AsyncAPIChannelBindings
- type AsyncAPIChannelReference
- type AsyncAPIComponents
- type AsyncAPIConfig
- type AsyncAPIInfo
- type AsyncAPIMessage
- type AsyncAPIMessageReference
- type AsyncAPIOperation
- type AsyncAPIOperationBindings
- type AsyncAPIParameter
- type AsyncAPIServer
- type AsyncAPISpec
- type AsyncAPITag
- type BunRouterAdapter
- func (a *BunRouterAdapter) Close() error
- func (a *BunRouterAdapter) Handle(method, path string, handler http.Handler)
- func (a *BunRouterAdapter) Mount(path string, handler http.Handler)
- func (a *BunRouterAdapter) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (a *BunRouterAdapter) UseGlobal(middleware func(http.Handler) http.Handler)
- type CallbackConfig
- type CallbackOperation
- type Components
- type Connection
- type Contact
- type Context
- type Controller
- type ControllerWithDependencies
- type ControllerWithMiddleware
- type ControllerWithPrefix
- type ControllerWithTags
- type Discriminator
- type DiscriminatorConfig
- type Encoding
- type EnumNamer
- type EnumValuer
- type ErrorHandler
- type Example
- type Extension
- type ExternalDocs
- type ExternalDocsDef
- type GroupConfig
- type GroupOption
- func WithGroupAuth(providerNames ...string) GroupOption
- func WithGroupAuthAnd(providerNames ...string) GroupOption
- func WithGroupInterceptor(interceptors ...Interceptor) GroupOption
- func WithGroupMetadata(key string, value any) GroupOption
- func WithGroupMiddleware(mw ...Middleware) GroupOption
- func WithGroupRequiredScopes(scopes ...string) GroupOption
- func WithGroupSkipInterceptor(names ...string) GroupOption
- func WithGroupTags(tags ...string) GroupOption
- type HTTPChannelBinding
- type HTTPError
- type Handler
- type HandlerPattern
- type Header
- type Info
- type Interceptor
- func AllowIPs(allowedIPs ...string) Interceptor
- func And(interceptors ...Interceptor) Interceptor
- func AuditLog(logger func(ctx Context, route RouteInfo, timestamp time.Time)) Interceptor
- func ChainInterceptors(interceptors ...Interceptor) Interceptor
- func DenyIPs(deniedIPs ...string) Interceptor
- func Enrich(name string, loader func(ctx Context, route RouteInfo) (map[string]any, error)) Interceptor
- func EnrichFromService[T any](serviceName string, loader func(ctx Context, svc T) (map[string]any, error)) Interceptor
- func EnrichUser(loader func(ctx Context) (any, error)) Interceptor
- func FeatureFlag(flagName string, checker func(ctx Context, flag string) bool) Interceptor
- func FeatureFlagFromContext(flagName string) Interceptor
- func FromFunc(fn InterceptorFunc) Interceptor
- func IfMetadata(key string, expectedValue any, interceptor Interceptor) Interceptor
- func IfTag(tag string, interceptor Interceptor) Interceptor
- func InterceptorFromFunc(fn InterceptorFunc) Interceptor
- func Maintenance(checker func() bool) Interceptor
- func Named(name string, interceptor Interceptor) Interceptor
- func NewInterceptor(name string, fn InterceptorFunc) Interceptor
- func Not(interceptor Interceptor, blockError error) Interceptor
- func Or(interceptors ...Interceptor) Interceptor
- func Parallel(interceptors ...Interceptor) Interceptor
- func ParallelAny(interceptors ...Interceptor) Interceptor
- func RateLimit(keyName string, checker func(ctx Context, key string) RateLimitResult) Interceptor
- func RateLimitByIP(checker func(ctx Context, ip string) RateLimitResult) Interceptor
- func RequireAllRoles(roles ...string) Interceptor
- func RequireAnyScope(scopes ...string) Interceptor
- func RequireAuth() Interceptor
- func RequireAuthProvider(providerName string) Interceptor
- func RequireContentType(contentTypes ...string) Interceptor
- func RequireHeader(headers ...string) Interceptor
- func RequireMetadata(key string, expectedValue any) Interceptor
- func RequireRole(roles ...string) Interceptor
- func RequireScopes(scopes ...string) Interceptor
- func RequireTag(tag string) Interceptor
- func TenantIsolation(tenantParamName string) Interceptor
- func TimeWindow(startHour, endHour int, location *time.Location) Interceptor
- func Unless(predicate func(ctx Context, route RouteInfo) bool, interceptor Interceptor) Interceptor
- func When(predicate func(ctx Context, route RouteInfo) bool, interceptor Interceptor) Interceptor
- type InterceptorChain
- type InterceptorFunc
- type InterceptorResult
- type InternalExtension
- type License
- type Link
- type Logger
- type MediaType
- type Middleware
- type MiddlewareFunc
- type OAuthFlow
- type OAuthFlows
- type OpenAPIConfig
- type OpenAPIServer
- type OpenAPISpec
- type OpenAPITag
- type Operation
- type Parameter
- type ParameterDef
- type PathItem
- type PathParam
- type PureMiddleware
- type RateLimitResult
- type RequestBody
- type RequestBodyDef
- type RequestComponents
- type Response
- type ResponseComponents
- type ResponseDef
- type ResponseSchemaDef
- type RouteConfig
- type RouteExtension
- type RouteInfo
- type RouteOption
- func WithAcceptedResponse() RouteOption
- func WithAsyncAPIBinding(bindingType string, binding any) RouteOption
- func WithAsyncAPIChannelDescription(description string) RouteOption
- func WithAsyncAPIChannelName(name string) RouteOption
- func WithAsyncAPIChannelSummary(summary string) RouteOption
- func WithAsyncAPIExternalDocs(url, description string) RouteOption
- func WithAsyncAPIOperationID(id string) RouteOption
- func WithAsyncAPISecurity(requirements map[string][]string) RouteOption
- func WithAsyncAPITags(tags ...string) RouteOption
- func WithAuth(providerNames ...string) RouteOption
- func WithAuthAnd(providerNames ...string) RouteOption
- func WithBatchResponse(itemType any, statusCode int) RouteOption
- func WithCallback(config CallbackConfig) RouteOption
- func WithCorrelationID(location, description string) RouteOption
- func WithCreatedResponse(resourceType any) RouteOption
- func WithDeprecated() RouteOption
- func WithDescription(desc string) RouteOption
- func WithDiscriminator(config DiscriminatorConfig) RouteOption
- func WithErrorResponses() RouteOption
- func WithExtension(name string, ext Extension) RouteOption
- func WithExternalDocs(description, url string) RouteOption
- func WithFileUploadResponse(statusCode int) RouteOption
- func WithHeaderSchema(schemaType any) RouteOption
- func WithInterceptor(interceptors ...Interceptor) RouteOption
- func WithListResponse(itemType any, statusCode int) RouteOption
- func WithMessageContentType(contentType string) RouteOption
- func WithMessageExample(direction, name string, example any) RouteOption
- func WithMessageExamples(direction string, examples map[string]any) RouteOption
- func WithMessageHeaders(headersSchema any) RouteOption
- func WithMetadata(key string, value any) RouteOption
- func WithMethod(method string) RouteOption
- func WithMiddleware(mw ...Middleware) RouteOption
- func WithName(name string) RouteOption
- func WithNoContentResponse() RouteOption
- func WithOperationID(id string) RouteOption
- func WithPaginatedResponse(itemType any, statusCode int) RouteOption
- func WithParameter(name, in, description string, required bool, example any) RouteOption
- func WithQuerySchema(schemaType any) RouteOption
- func WithRequestBody(description string, required bool, example any) RouteOption
- func WithRequestBodySchema(schemaOrType any) RouteOption
- func WithRequestContentTypes(types ...string) RouteOption
- func WithRequestExample(name string, example any) RouteOption
- func WithRequestSchema(schemaOrType any) RouteOption
- func WithRequiredAuth(providerName string, scopes ...string) RouteOption
- func WithResponse(code int, description string, example any) RouteOption
- func WithResponseContentTypes(types ...string) RouteOption
- func WithResponseExample(statusCode int, name string, example any) RouteOption
- func WithResponseSchema(statusCode int, description string, schemaOrType any) RouteOption
- func WithSSEMessage(eventName string, schema any) RouteOption
- func WithSSEMessages(messageSchemas map[string]any) RouteOption
- func WithSchemaRef(name string, schema any) RouteOption
- func WithSecurity(schemes ...string) RouteOption
- func WithSensitiveFieldCleaning() RouteOption
- func WithServerProtocol(serverNames ...string) RouteOption
- func WithSkipInterceptor(names ...string) RouteOption
- func WithStandardRESTResponses(resourceType any) RouteOption
- func WithStrictValidation() RouteOption
- func WithSummary(summary string) RouteOption
- func WithTags(tags ...string) RouteOption
- func WithTimeout(d time.Duration) RouteOption
- func WithValidation(enabled bool) RouteOption
- func WithValidationErrorResponse() RouteOption
- func WithWebSocketMessages(sendSchema, receiveSchema any) RouteOption
- func WithWebTransport(config WebTransportConfig) RouteOption
- func WithWebTransportDatagrams(enabled bool) RouteOption
- func WithWebTransportStreams(maxBidi, maxUni int64) RouteOption
- func WithWebhook(name string, operation *CallbackOperation) RouteOption
- type Router
- type RouterAdapter
- type RouterOption
- func WithAdapter(adapter RouterAdapter) RouterOption
- func WithAsyncAPI(config AsyncAPIConfig) RouterOption
- func WithContainer(container di.Container) RouterOption
- func WithErrorHandler(handler ErrorHandler) RouterOption
- func WithHealth(config shared.HealthConfig) RouterOption
- func WithLogger(logger Logger) RouterOption
- func WithMetrics(config shared.MetricsConfig) RouterOption
- func WithOpenAPI(config OpenAPIConfig) RouterOption
- func WithRecovery() RouterOption
- type SSEHandler
- type Schema
- type SchemaValidator
- type SecurityRequirement
- type SecurityScheme
- type Stream
- type StreamConfig
- type ValidationError
- type ValidationErrorResponse
- type ValidationErrors
- type WebSocketChannelBinding
- type WebSocketHandler
- type WebTransportConfig
- type WebTransportHandler
- type WebTransportSession
- type WebTransportStream
Constants ¶
const ( ErrCodeRequired = shared.ErrCodeRequired ErrCodeInvalidType = shared.ErrCodeInvalidType ErrCodeInvalidFormat = shared.ErrCodeInvalidFormat ErrCodeMinLength = shared.ErrCodeMinLength ErrCodeMaxLength = shared.ErrCodeMaxLength ErrCodeMinValue = shared.ErrCodeMinValue ErrCodeMaxValue = shared.ErrCodeMaxValue ErrCodePattern = shared.ErrCodePattern ErrCodeEnum = shared.ErrCodeEnum ErrCodeMinItems = shared.ErrCodeMinItems ErrCodeMaxItems = shared.ErrCodeMaxItems ErrCodeUniqueItems = shared.ErrCodeUniqueItems )
Re-export validation error codes
const (
// ContextKeySensitiveFieldCleaning is the context key for sensitive field cleaning flag.
ContextKeySensitiveFieldCleaning = "forge:sensitive_field_cleaning"
)
Context keys for internal use.
const ManagerKey = shared.RouterKey
ManagerKey is the DI key for the router service.
const ParamsContextKey = "forge:params"
ParamsContextKey is used to store route params in request context Exported so di.NewContext can use the same key.
Variables ¶
var ( NewHTTPError = errors.NewHTTPError BadRequest = errors.BadRequest Forbidden = errors.Forbidden NotFound = errors.NotFound InternalError = errors.InternalError )
var ( NewValidationErrors = shared.NewValidationErrors NewValidationErrorResponse = shared.NewValidationErrorResponse )
Re-export validation functions
Functions ¶
func ConvertPathToOpenAPIFormat ¶ added in v0.7.0
ConvertPathToOpenAPIFormat converts a path with :param style parameters to OpenAPI's {param} style format. e.g., /api/workspaces/:workspace_id/users -> /api/workspaces/{workspace_id}/users
func FormatValidationError ¶
FormatValidationError formats validation errors for HTTP response.
func GetTypeName ¶
GetTypeName returns a qualified type name for schema references.
func ValidateQueryParams ¶
ValidateQueryParams validates query parameters against a struct schema.
Types ¶
type AsyncAPIChannel ¶
type AsyncAPIChannel = shared.AsyncAPIChannel
Type aliases for AsyncAPI types.
type AsyncAPIChannelBindings ¶
type AsyncAPIChannelBindings = shared.AsyncAPIChannelBindings
Type aliases for AsyncAPI types.
type AsyncAPIChannelReference ¶
type AsyncAPIChannelReference = shared.AsyncAPIChannelReference
Type aliases for AsyncAPI types.
type AsyncAPIComponents ¶
type AsyncAPIComponents = shared.AsyncAPIComponents
Type aliases for AsyncAPI types.
type AsyncAPIMessage ¶
type AsyncAPIMessage = shared.AsyncAPIMessage
Type aliases for AsyncAPI types.
type AsyncAPIMessageReference ¶
type AsyncAPIMessageReference = shared.AsyncAPIMessageReference
Type aliases for AsyncAPI types.
type AsyncAPIOperation ¶
type AsyncAPIOperation = shared.AsyncAPIOperation
Type aliases for AsyncAPI types.
type AsyncAPIOperationBindings ¶
type AsyncAPIOperationBindings = shared.AsyncAPIOperationBindings
Type aliases for AsyncAPI types.
type AsyncAPIParameter ¶
type AsyncAPIParameter = shared.AsyncAPIParameter
type BunRouterAdapter ¶
type BunRouterAdapter struct {
// contains filtered or unexported fields
}
BunRouterAdapter wraps uptrace/bunrouter.
func (*BunRouterAdapter) Close ¶
func (a *BunRouterAdapter) Close() error
Close cleans up resources.
func (*BunRouterAdapter) Handle ¶
func (a *BunRouterAdapter) Handle(method, path string, handler http.Handler)
Handle registers a route.
func (*BunRouterAdapter) Mount ¶
func (a *BunRouterAdapter) Mount(path string, handler http.Handler)
Mount registers a sub-handler.
func (*BunRouterAdapter) ServeHTTP ¶
func (a *BunRouterAdapter) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP dispatches requests.
func (*BunRouterAdapter) UseGlobal ¶ added in v0.7.0
func (a *BunRouterAdapter) UseGlobal(middleware func(http.Handler) http.Handler)
UseGlobal registers global middleware that runs before routing. This middleware will run for ALL requests, even those that don't match any route. This is critical for CORS preflight handling.
type CallbackConfig ¶
type CallbackConfig struct {
Name string
Expression string // Callback URL expression (e.g., "{$request.body#/callbackUrl}")
Operations map[string]*CallbackOperation
}
CallbackConfig defines a callback (webhook) for an operation.
func NewCompletionCallbackConfig ¶
func NewCompletionCallbackConfig(callbackURLExpression string, resultSchema any) CallbackConfig
NewCompletionCallbackConfig creates a callback config for async operation completion.
func NewEventCallbackConfig ¶
func NewEventCallbackConfig(callbackURLExpression string, eventSchema any) CallbackConfig
NewEventCallbackConfig creates a callback config for event notifications.
func NewStatusCallbackConfig ¶
func NewStatusCallbackConfig(callbackURLExpression string, statusSchema any) CallbackConfig
NewStatusCallbackConfig creates a callback config for status updates.
type CallbackOperation ¶
type CallbackOperation struct {
Summary string
Description string
RequestBody *RequestBody
Responses map[string]*Response
}
CallbackOperation defines an operation that will be called back.
func NewCallbackOperation ¶
func NewCallbackOperation(summary, description string) *CallbackOperation
NewCallbackOperation creates a new callback operation.
func (*CallbackOperation) WithCallbackRequestBody ¶
func (co *CallbackOperation) WithCallbackRequestBody(description string, schema any) *CallbackOperation
WithCallbackRequestBody sets the request body for a callback operation.
func (*CallbackOperation) WithCallbackResponse ¶
func (co *CallbackOperation) WithCallbackResponse(statusCode int, description string) *CallbackOperation
WithCallbackResponse adds a response to a callback operation.
type Components ¶
type Components = shared.Components
Components holds reusable objects for the API spec.
type Connection ¶
type Connection interface {
// ID returns unique connection ID
ID() string
// Read reads a message from the connection
Read() ([]byte, error)
// ReadJSON reads JSON from the connection
ReadJSON(v any) error
// Write sends a message to the connection
Write(data []byte) error
// WriteJSON sends JSON to the connection
WriteJSON(v any) error
// Close closes the connection
Close() error
// Context returns the connection context
Context() context.Context
// RemoteAddr returns the remote address
RemoteAddr() string
// LocalAddr returns the local address
LocalAddr() string
}
Connection represents a WebSocket connection.
type Controller ¶
type Controller interface {
// Name returns the controller identifier
Name() string
// Routes registers routes on the router
Routes(r Router) error
}
Controller organizes related routes.
type ControllerWithDependencies ¶
type ControllerWithDependencies interface {
Controller
Dependencies() []string
}
ControllerWithDependencies declares dependencies for ordering.
type ControllerWithMiddleware ¶
type ControllerWithMiddleware interface {
Controller
Middleware() []Middleware
}
ControllerWithMiddleware applies middleware to all routes.
type ControllerWithPrefix ¶
type ControllerWithPrefix interface {
Controller
Prefix() string
}
ControllerWithPrefix sets a path prefix for all routes.
type ControllerWithTags ¶
type ControllerWithTags interface {
Controller
Tags() []string
}
ControllerWithTags adds metadata tags to all routes.
type DiscriminatorConfig ¶
DiscriminatorConfig defines discriminator for polymorphic types.
type EnumNamer ¶ added in v0.7.0
EnumNamer is an optional interface that enum types can implement to provide a custom component name in the OpenAPI schema.
type EnumValuer ¶ added in v0.7.0
type EnumValuer = shared.EnumValuer
EnumValuer is an optional interface that enum types can implement to provide their possible values for OpenAPI schema generation.
type ErrorHandler ¶
type ErrorHandler = shared.ErrorHandler
ErrorHandler handles errors from handlers.
func NewDefaultErrorHandler ¶
func NewDefaultErrorHandler(l Logger) ErrorHandler
NewDefaultErrorHandler creates a default error handler.
type Extension ¶
type Extension interface {
// Name returns the unique name of the extension
Name() string
// Version returns the semantic version of the extension
Version() string
// Description returns a human-readable description
Description() string
// Start starts the extension.
// This is called after all extensions have been registered and the DI container has started.
Start(ctx context.Context) error
// Stop stops the extension gracefully.
// Extensions are stopped in reverse dependency order.
Stop(ctx context.Context) error
// Health checks if the extension is healthy.
// This is called periodically by the health check system.
// Return nil if healthy, error otherwise.
Health(ctx context.Context) error
// Dependencies returns the names of extensions this extension depends on.
// The app will ensure dependencies are started before this extension.
Dependencies() []string
}
Extension represents an official Forge extension that can be registered with an App. Extensions have full access to the framework and are first-party, trusted components.
Extensions follow a standard lifecycle:
- Register(app) - Register services with DI container
- Start(ctx) - Start the extension
- Health(ctx) - Check extension health (called periodically)
- Stop(ctx) - Stop the extension (called during graceful shutdown)
type ExternalDocs ¶
type ExternalDocs = shared.ExternalDocs
ExternalDocs points to external documentation.
type ExternalDocsDef ¶
ExternalDocsDef defines external documentation.
type GroupConfig ¶
type GroupConfig struct {
Middleware []Middleware
Tags []string
Metadata map[string]any
// Interceptors inherited by all routes in the group
Interceptors []Interceptor
SkipInterceptors map[string]bool // Names of interceptors to skip
}
GroupConfig holds route group configuration.
type GroupOption ¶
type GroupOption interface {
Apply(*GroupConfig)
}
GroupOption configures a route group.
func WithGroupAuth ¶
func WithGroupAuth(providerNames ...string) GroupOption
WithGroupAuth adds authentication to all routes in a group. Multiple providers create an OR condition.
Example:
api := router.Group("/api", forge.WithGroupAuth("jwt"))
func WithGroupAuthAnd ¶
func WithGroupAuthAnd(providerNames ...string) GroupOption
WithGroupAuthAnd requires all providers to succeed for all routes in the group.
func WithGroupInterceptor ¶ added in v0.7.0
func WithGroupInterceptor(interceptors ...Interceptor) GroupOption
WithGroupInterceptor adds interceptors to all routes in a group. Group interceptors run before route-specific interceptors. These interceptors are inherited by nested groups.
Example:
adminAPI := router.Group("/admin",
forge.WithGroupInterceptor(RequireAuth(), RequireAdmin),
)
// All routes in this group require auth and admin role
adminAPI.GET("/users", listUsers)
adminAPI.DELETE("/users/:id", deleteUser)
func WithGroupMetadata ¶
func WithGroupMetadata(key string, value any) GroupOption
func WithGroupMiddleware ¶
func WithGroupMiddleware(mw ...Middleware) GroupOption
Group option constructors.
func WithGroupRequiredScopes ¶
func WithGroupRequiredScopes(scopes ...string) GroupOption
WithGroupRequiredScopes sets required scopes for all routes in a group.
func WithGroupSkipInterceptor ¶ added in v0.7.0
func WithGroupSkipInterceptor(names ...string) GroupOption
WithGroupSkipInterceptor skips named interceptors for all routes in a group. Useful for excluding parent group interceptors from a nested group.
Example:
api := router.Group("/api",
forge.WithGroupInterceptor(RateLimitInterceptor),
)
// Nested group without rate limiting
internal := api.Group("/internal",
forge.WithGroupSkipInterceptor("rate-limit"),
)
func WithGroupTags ¶
func WithGroupTags(tags ...string) GroupOption
type HTTPChannelBinding ¶
type HTTPChannelBinding = shared.HTTPChannelBinding
Type aliases for AsyncAPI types.
type Handler ¶ added in v0.5.0
Handler is a forge handler function that takes a Context and returns an error This is the preferred handler pattern for forge applications.
type HandlerPattern ¶
type HandlerPattern int
HandlerPattern indicates the handler signature.
const ( PatternStandard HandlerPattern = iota // func(w, r) PatternContext // func(ctx) error PatternOpinionated // func(ctx, req) (resp, error) PatternService // func(ctx, svc) error PatternCombined // func(ctx, svc, req) (resp, error) )
type Interceptor ¶ added in v0.7.0
type Interceptor interface {
// Name returns the unique identifier for this interceptor.
// Used for skipping, debugging, and logging.
Name() string
// Intercept executes the interceptor logic.
Intercept(ctx Context, route RouteInfo) InterceptorResult
}
Interceptor represents a named interceptor with metadata. Named interceptors can be skipped on specific routes.
func AllowIPs ¶ added in v0.7.0
func AllowIPs(allowedIPs ...string) Interceptor
AllowIPs creates an interceptor that only allows specific IP addresses.
func And ¶ added in v0.7.0
func And(interceptors ...Interceptor) Interceptor
And combines interceptors sequentially - ALL must pass. Executes in order, short-circuits on first block. Values from all interceptors are merged into context as they complete.
Example:
router.POST("/admin/users", handler,
forge.WithInterceptor(
And(RequireAuth(), RequireRole("admin"), RequireScopes("write:users")),
),
)
func AuditLog ¶ added in v0.7.0
func AuditLog(logger func(ctx Context, route RouteInfo, timestamp time.Time)) Interceptor
AuditLog creates an interceptor that logs access attempts. The logger function is called with audit information.
func ChainInterceptors ¶ added in v0.7.0
func ChainInterceptors(interceptors ...Interceptor) Interceptor
ChainInterceptors combines multiple interceptors into a single interceptor. All interceptors are executed in order; all must pass. This is equivalent to And() but more explicit about sequential execution.
func DenyIPs ¶ added in v0.7.0
func DenyIPs(deniedIPs ...string) Interceptor
DenyIPs creates an interceptor that blocks specific IP addresses.
func Enrich ¶ added in v0.7.0
func Enrich(name string, loader func(ctx Context, route RouteInfo) (map[string]any, error)) Interceptor
Enrich creates an interceptor that enriches the context with values. The loader function is called to fetch data to inject.
func EnrichFromService ¶ added in v0.7.0
func EnrichFromService[T any](serviceName string, loader func(ctx Context, svc T) (map[string]any, error)) Interceptor
EnrichFromService creates an interceptor that loads data from a DI service.
func EnrichUser ¶ added in v0.7.0
func EnrichUser(loader func(ctx Context) (any, error)) Interceptor
EnrichUser creates an interceptor that loads user data into context under "user" key.
func FeatureFlag ¶ added in v0.7.0
func FeatureFlag(flagName string, checker func(ctx Context, flag string) bool) Interceptor
FeatureFlag creates an interceptor that checks if a feature is enabled. The checker function determines if the feature is enabled for the current request.
func FeatureFlagFromContext ¶ added in v0.7.0
func FeatureFlagFromContext(flagName string) Interceptor
FeatureFlagFromContext creates an interceptor that checks a feature flag from context. Expects a "feature-flags" map[string]bool in context.
func FromFunc ¶ added in v0.7.0
func FromFunc(fn InterceptorFunc) Interceptor
FromFunc creates an anonymous interceptor from a simple function. Equivalent to InterceptorFromFunc but with a clearer name.
func IfMetadata ¶ added in v0.7.0
func IfMetadata(key string, expectedValue any, interceptor Interceptor) Interceptor
IfMetadata conditionally executes an interceptor based on route metadata. If the metadata key doesn't exist or doesn't match the expected value, skips the interceptor.
Example:
// Only run rate limiting on routes marked for it
router.GET("/api/data", handler,
forge.WithMetadata("rate-limit", true),
forge.WithInterceptor(
IfMetadata("rate-limit", true, RateLimitInterceptor),
),
)
func IfTag ¶ added in v0.7.0
func IfTag(tag string, interceptor Interceptor) Interceptor
IfTag conditionally executes an interceptor based on route tags. If the route doesn't have the specified tag, skips the interceptor.
Example:
// Only audit routes tagged as "sensitive"
router.POST("/api/payment", handler,
forge.WithTags("sensitive"),
forge.WithInterceptor(
IfTag("sensitive", AuditLogInterceptor),
),
)
func InterceptorFromFunc ¶ added in v0.7.0
func InterceptorFromFunc(fn InterceptorFunc) Interceptor
InterceptorFromFunc creates an anonymous interceptor from a function. Anonymous interceptors cannot be skipped by name. Use NewInterceptor for interceptors that may need to be skipped.
func Maintenance ¶ added in v0.7.0
func Maintenance(checker func() bool) Interceptor
Maintenance creates an interceptor that blocks requests during maintenance. The checker function returns true if maintenance mode is active.
func Named ¶ added in v0.7.0
func Named(name string, interceptor Interceptor) Interceptor
Named wraps an anonymous interceptor with a name. Useful for making interceptors skippable.
func NewInterceptor ¶ added in v0.7.0
func NewInterceptor(name string, fn InterceptorFunc) Interceptor
NewInterceptor creates a named interceptor from a function. Named interceptors can be skipped using WithSkipInterceptor.
Example:
var RequireAdmin = NewInterceptor("require-admin", func(ctx Context, route RouteInfo) InterceptorResult {
if ctx.Get("user.role") != "admin" {
return Block(Forbidden("admin access required"))
}
return Allow()
})
func Not ¶ added in v0.7.0
func Not(interceptor Interceptor, blockError error) Interceptor
Not inverts an interceptor's decision. If the interceptor blocks, Not allows. If it allows, Not blocks with the provided error.
Example:
// Block if user IS an admin (inverse check)
var BlockAdmins = Not(RequireRole("admin"), Forbidden("admins cannot access this"))
func Or ¶ added in v0.7.0
func Or(interceptors ...Interceptor) Interceptor
Or combines interceptors sequentially - ANY one passing is sufficient. Executes in order, short-circuits on first success.
Example:
router.GET("/api/data", handler,
forge.WithInterceptor(
Or(RequireAuth(), RequireAPIKey()),
),
)
func Parallel ¶ added in v0.7.0
func Parallel(interceptors ...Interceptor) Interceptor
Parallel executes interceptors concurrently and collects results. ALL interceptors must pass for the request to proceed. If any interceptor blocks, the first blocking error is returned. Values from all passing interceptors are merged.
Example:
// Load user data concurrently
router.GET("/dashboard", handler,
forge.WithInterceptor(
Parallel(
EnrichUser(loadUser),
Enrich("prefs", loadPreferences),
Enrich("notifications", loadNotifications),
),
),
)
func ParallelAny ¶ added in v0.7.0
func ParallelAny(interceptors ...Interceptor) Interceptor
ParallelAny executes interceptors concurrently. ANY one passing is sufficient to proceed. Returns as soon as one interceptor allows. This is useful for "any of these auth methods" scenarios.
Example:
// Any authentication method works
router.GET("/api/data", handler,
forge.WithInterceptor(
ParallelAny(
RequireAuthProvider("jwt"),
RequireAuthProvider("api-key"),
RequireAuthProvider("oauth2"),
),
),
)
func RateLimit ¶ added in v0.7.0
func RateLimit(keyName string, checker func(ctx Context, key string) RateLimitResult) Interceptor
RateLimit creates a rate limit interceptor. The checker function should return the rate limit status for the given key. Rate limit info is added to context for response headers.
func RateLimitByIP ¶ added in v0.7.0
func RateLimitByIP(checker func(ctx Context, ip string) RateLimitResult) Interceptor
RateLimitByIP creates a rate limit interceptor keyed by client IP.
func RequireAllRoles ¶ added in v0.7.0
func RequireAllRoles(roles ...string) Interceptor
RequireAllRoles creates an interceptor that requires ALL specified roles. Checks the "user.roles" context value (expected to be []string).
func RequireAnyScope ¶ added in v0.7.0
func RequireAnyScope(scopes ...string) Interceptor
RequireAnyScope creates an interceptor that requires ANY of the specified scopes. At least one scope must be present.
func RequireAuth ¶ added in v0.7.0
func RequireAuth() Interceptor
RequireAuth creates an interceptor that requires authentication. Checks for "auth" or "user" in the context (typically set by auth middleware).
func RequireAuthProvider ¶ added in v0.7.0
func RequireAuthProvider(providerName string) Interceptor
RequireAuthProvider creates an interceptor that requires a specific auth provider. Checks the "auth.provider" context value.
func RequireContentType ¶ added in v0.7.0
func RequireContentType(contentTypes ...string) Interceptor
RequireContentType creates an interceptor that requires a specific Content-Type.
func RequireHeader ¶ added in v0.7.0
func RequireHeader(headers ...string) Interceptor
RequireHeader creates an interceptor that requires specific headers to be present.
func RequireMetadata ¶ added in v0.7.0
func RequireMetadata(key string, expectedValue any) Interceptor
RequireMetadata creates an interceptor that checks route metadata.
func RequireRole ¶ added in v0.7.0
func RequireRole(roles ...string) Interceptor
RequireRole creates an interceptor that requires ANY of the specified roles. Checks the "user.role" context value.
func RequireScopes ¶ added in v0.7.0
func RequireScopes(scopes ...string) Interceptor
RequireScopes creates an interceptor that requires ALL specified scopes. Checks the "auth.scopes" context value (expected to be []string).
func RequireTag ¶ added in v0.7.0
func RequireTag(tag string) Interceptor
RequireTag creates an interceptor that checks if route has a specific tag.
func TenantIsolation ¶ added in v0.7.0
func TenantIsolation(tenantParamName string) Interceptor
TenantIsolation creates an interceptor that validates tenant access. Compares the tenant from the URL param with the user's tenant.
func TimeWindow ¶ added in v0.7.0
func TimeWindow(startHour, endHour int, location *time.Location) Interceptor
TimeWindow creates an interceptor that only allows requests during specific hours. Hours are in 24-hour format (0-23) in the specified timezone.
func Unless ¶ added in v0.7.0
func Unless(predicate func(ctx Context, route RouteInfo) bool, interceptor Interceptor) Interceptor
Unless conditionally skips an interceptor based on a predicate. If the predicate returns true, the interceptor is skipped (allows). This is the inverse of When.
Example:
// Skip auth for requests with valid API key header
router.GET("/api/data", handler,
forge.WithInterceptor(
Unless(func(ctx Context, route RouteInfo) bool {
return ctx.Header("X-API-Key") != ""
}, RequireAuth()),
),
)
func When ¶ added in v0.7.0
func When(predicate func(ctx Context, route RouteInfo) bool, interceptor Interceptor) Interceptor
When conditionally executes an interceptor based on a predicate. If the predicate returns false, the interceptor is skipped (allows).
Example:
// Only require bulk scope for bulk operations
router.POST("/api/resource", handler,
forge.WithInterceptor(
When(func(ctx Context, route RouteInfo) bool {
return ctx.Header("X-Bulk-Operation") == "true"
}, RequireScopes("bulk:write")),
),
)
type InterceptorChain ¶ added in v0.7.0
type InterceptorChain struct {
// contains filtered or unexported fields
}
InterceptorChain represents a chain of interceptors with skip configuration. This is used internally by the router to manage interceptors for a route.
func NewInterceptorChain ¶ added in v0.7.0
func NewInterceptorChain(interceptors []Interceptor, skipSet map[string]bool) *InterceptorChain
NewInterceptorChain creates a new interceptor chain.
func (*InterceptorChain) Empty ¶ added in v0.7.0
func (c *InterceptorChain) Empty() bool
Empty returns true if the chain has no interceptors.
func (*InterceptorChain) Execute ¶ added in v0.7.0
func (c *InterceptorChain) Execute(ctx Context, route RouteInfo) error
Execute runs all interceptors in the chain. Returns an error if any interceptor blocks.
func (*InterceptorChain) Len ¶ added in v0.7.0
func (c *InterceptorChain) Len() int
Len returns the number of interceptors in the chain.
type InterceptorFunc ¶ added in v0.7.0
type InterceptorFunc func(ctx Context, route RouteInfo) InterceptorResult
InterceptorFunc is a function that inspects a request and decides whether to allow it to proceed.
Interceptors receive:
- ctx: The forge Context with full request access
- route: Full RouteInfo for permission/config checking
Return InterceptorResult using convenience functions:
- Allow() - proceed to handler
- AllowWithValues(map) - proceed and enrich context
- Block(err) - reject request with error
type InterceptorResult ¶ added in v0.7.0
type InterceptorResult struct {
// Blocked indicates the request should not proceed
Blocked bool
// Error is returned when the interceptor blocks the request
Error error
// Values to merge into the context (enrichment)
// These are merged with existing context values, not replaced
Values map[string]any
}
InterceptorResult represents the outcome of an interceptor execution. Interceptors can either allow the request to proceed, block it, or enrich the context.
func Allow ¶ added in v0.7.0
func Allow() InterceptorResult
Allow returns a result that allows the request to proceed.
func AllowWithValues ¶ added in v0.7.0
func AllowWithValues(values map[string]any) InterceptorResult
AllowWithValues allows the request and enriches the context with values. Values are merged with existing context values.
func Block ¶ added in v0.7.0
func Block(err error) InterceptorResult
Block returns a result that blocks the request with an error.
func BlockWithValues ¶ added in v0.7.0
func BlockWithValues(err error, values map[string]any) InterceptorResult
BlockWithValues blocks the request but still provides values (useful for debugging/logging).
type InternalExtension ¶ added in v0.7.0
type InternalExtension interface {
// ExcludeFromSchemas returns true if all routes from this extension
// should be excluded from schema generation (OpenAPI, AsyncAPI, oRPC).
ExcludeFromSchemas() bool
}
InternalExtension is an optional interface that extensions can implement to indicate that all their routes should be excluded from schema generation.
This is useful for:
- Internal monitoring/metrics extensions
- Debug/development extensions
- Admin/management extensions
- Infrastructure extensions
Example:
type DebugExtension struct {
forge.ExtensionBase
}
func (e *DebugExtension) ExcludeFromSchemas() bool {
return true
}
Routes registered by this extension will automatically be excluded from OpenAPI, AsyncAPI, and oRPC schema generation.
type Middleware ¶
Middleware wraps forge handlers (new pattern) This is the preferred middleware pattern for forge applications.
func Chain ¶
func Chain(middlewares ...Middleware) Middleware
Chain combines multiple middleware into a single middleware Middleware are applied in the order they are provided The first middleware in the list wraps the outermost, last wraps the innermost.
func CreateValidationMiddleware ¶
func CreateValidationMiddleware(validator *SchemaValidator) Middleware
CreateValidationMiddleware creates a middleware that validates requests against schemas.
type MiddlewareFunc ¶
MiddlewareFunc is a convenience type for middleware functions that want to explicitly call the next handler Note: This is a legacy type for http.Handler based middleware For new code, use Middleware directly (func(next Handler) Handler).
func (MiddlewareFunc) ToMiddleware ¶
func (f MiddlewareFunc) ToMiddleware(container di.Container) Middleware
ToMiddleware converts a MiddlewareFunc to a Middleware This requires a container to create forge contexts.
type OpenAPIConfig ¶
type OpenAPIConfig = shared.OpenAPIConfig
OpenAPIConfig configures OpenAPI 3.1.0 generation.
type OpenAPIServer ¶
type OpenAPIServer = shared.OpenAPIServer
OpenAPIServer represents a server in the OpenAPI spec.
type OpenAPISpec ¶
type OpenAPISpec = shared.OpenAPISpec
OpenAPISpec represents the complete OpenAPI 3.1.0 specification.
type OpenAPITag ¶
type OpenAPITag = shared.OpenAPITag
OpenAPITag represents a tag in the OpenAPI spec.
type ParameterDef ¶
ParameterDef defines a parameter.
type PureMiddleware ¶ added in v0.5.0
PureMiddleware wraps HTTP handlers.
func FromMiddleware ¶ added in v0.5.0
func FromMiddleware(m Middleware) PureMiddleware
FromMiddleware converts a Middleware to PureMiddleware This is a convenience wrapper that requires container and errorHandler For use cases where container is not available, use ToPureMiddleware directly.
func ToPureMiddleware ¶ added in v0.5.0
func ToPureMiddleware(m Middleware, container di.Container, errorHandler ErrorHandler) PureMiddleware
ToPureMiddleware converts a Middleware (forge middleware) to a PureMiddleware (http middleware) This allows forge middlewares to work with http.Handler based systems.
func (PureMiddleware) ToMiddleware ¶ added in v0.5.0
func (m PureMiddleware) ToMiddleware() Middleware
ToMiddleware converts a ForgeMiddleware to a legacy Middleware This allows forge middlewares to work with the existing router.
type RateLimitResult ¶ added in v0.7.0
RateLimitResult contains rate limit check results.
type RequestBody ¶
type RequestBody = shared.RequestBody
RequestBody describes a single request body.
type RequestBodyDef ¶
RequestBodyDef defines a request body.
type RequestComponents ¶
type RequestComponents struct {
PathParams []Parameter
QueryParams []Parameter
HeaderParams []Parameter
BodySchema *Schema
HasBody bool
IsMultipart bool // true if the schema contains file uploads or form:"" tags
}
RequestComponents holds all components of a request extracted from a unified schema.
type ResponseComponents ¶ added in v0.7.0
type ResponseComponents struct {
Headers map[string]*Header
BodySchema *Schema
HasBody bool
BodySchemaName string // Custom schema name from schema:"name" tag
}
ResponseComponents holds all components of a response extracted from a unified schema.
type ResponseDef ¶
ResponseDef defines a response.
type ResponseSchemaDef ¶
ResponseSchemaDef defines a response schema.
type RouteConfig ¶
type RouteConfig struct {
Name string
Method string // HTTP method override (for SSE, WebSocket, etc.)
Summary string
Description string
Tags []string
Middleware []Middleware
Timeout time.Duration
Metadata map[string]any
Extensions map[string]Extension
// Interceptors run before the handler (after middleware)
// Unlike middleware, interceptors don't wrap the handler chain -
// they simply allow/block the request or enrich the context.
Interceptors []Interceptor
SkipInterceptors map[string]bool // Names of interceptors to skip
// OpenAPI metadata
OperationID string
Deprecated bool
// SensitiveFieldCleaning enables cleaning of sensitive fields in responses.
SensitiveFieldCleaning bool
}
RouteConfig holds route configuration.
type RouteExtension ¶
RouteExtension represents a route-level extension (e.g., OpenAPI, custom validation) Note: This is different from app-level Extension which manages app components.
type RouteInfo ¶
type RouteInfo struct {
Name string
Method string
Path string
Pattern string
Handler any
Middleware []Middleware
Tags []string
Metadata map[string]any
Extensions map[string]Extension
Summary string
Description string
// Interceptors provides access to route interceptors for inspection
Interceptors []Interceptor
SkipInterceptors map[string]bool
// SensitiveFieldCleaning indicates if sensitive fields should be cleaned in responses.
SensitiveFieldCleaning bool
}
RouteInfo provides route information for inspection.
type RouteOption ¶
type RouteOption interface {
Apply(*RouteConfig)
}
RouteOption configures a route.
func WithAcceptedResponse ¶
func WithAcceptedResponse() RouteOption
WithAcceptedResponse creates a 202 Accepted response for async operations.
func WithAsyncAPIBinding ¶
func WithAsyncAPIBinding(bindingType string, binding any) RouteOption
WithAsyncAPIBinding adds protocol-specific bindings bindingType: "ws" or "http" or "server" or "channel" or "operation" or "message" binding: the binding object (e.g., WebSocketChannelBinding, HTTPServerBinding)
func WithAsyncAPIChannelDescription ¶
func WithAsyncAPIChannelDescription(description string) RouteOption
WithAsyncAPIChannelDescription sets the channel description.
func WithAsyncAPIChannelName ¶
func WithAsyncAPIChannelName(name string) RouteOption
WithAsyncAPIChannelName sets a custom channel name (overrides path-based naming).
func WithAsyncAPIChannelSummary ¶
func WithAsyncAPIChannelSummary(summary string) RouteOption
WithAsyncAPIChannelSummary sets the channel summary.
func WithAsyncAPIExternalDocs ¶
func WithAsyncAPIExternalDocs(url, description string) RouteOption
WithAsyncAPIExternalDocs adds external documentation link.
func WithAsyncAPIOperationID ¶
func WithAsyncAPIOperationID(id string) RouteOption
WithAsyncAPIOperationID sets a custom operation ID for AsyncAPI.
func WithAsyncAPISecurity ¶
func WithAsyncAPISecurity(requirements map[string][]string) RouteOption
WithAsyncAPISecurity adds security requirements to the operation.
func WithAsyncAPITags ¶
func WithAsyncAPITags(tags ...string) RouteOption
WithAsyncAPITags adds tags to the AsyncAPI operation.
func WithAuth ¶
func WithAuth(providerNames ...string) RouteOption
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 WithAuthAnd ¶
func WithAuthAnd(providerNames ...string) RouteOption
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 WithBatchResponse ¶
func WithBatchResponse(itemType any, statusCode int) RouteOption
WithBatchResponse creates a response for batch operations.
func WithCallback ¶
func WithCallback(config CallbackConfig) RouteOption
WithCallback adds a callback definition to a route.
func WithCorrelationID ¶
func WithCorrelationID(location, description string) RouteOption
WithCorrelationID adds correlation ID configuration for request-reply patterns location: runtime expression like "$message.header#/correlationId" description: description of the correlation ID
func WithCreatedResponse ¶
func WithCreatedResponse(resourceType any) RouteOption
WithCreatedResponse creates a 201 Created response with Location header.
func WithDeprecated ¶
func WithDeprecated() RouteOption
func WithDescription ¶
func WithDescription(desc string) RouteOption
func WithDiscriminator ¶
func WithDiscriminator(config DiscriminatorConfig) RouteOption
WithDiscriminator adds discriminator support for polymorphic schemas.
func WithErrorResponses ¶
func WithErrorResponses() RouteOption
WithErrorResponses adds standard HTTP error responses to a route Includes 400, 401, 403, 404, 500.
func WithExtension ¶
func WithExtension(name string, ext Extension) RouteOption
func WithExternalDocs ¶
func WithExternalDocs(description, url string) RouteOption
WithExternalDocs adds external documentation link.
func WithFileUploadResponse ¶
func WithFileUploadResponse(statusCode int) RouteOption
WithFileUploadResponse creates a response for file upload success.
func WithHeaderSchema ¶
func WithHeaderSchema(schemaType any) RouteOption
WithHeaderSchema sets the header parameters schema for OpenAPI generation schemaType should be a struct with header tags.
func WithInterceptor ¶ added in v0.7.0
func WithInterceptor(interceptors ...Interceptor) RouteOption
WithInterceptor adds interceptors to a route. Interceptors run in order before the handler. If any interceptor blocks, subsequent interceptors and the handler are not executed.
Interceptors are different from middleware:
- Middleware wraps the handler chain (before/after)
- Interceptors run before the handler only, with a simple allow/block decision
- Interceptors can enrich the context with values
- Interceptors can be skipped by name
Example:
router.POST("/admin/users", handler,
forge.WithInterceptor(RequireAdmin, RateLimitCheck),
)
func WithListResponse ¶
func WithListResponse(itemType any, statusCode int) RouteOption
WithListResponse creates a simple list response (array of items).
func WithMessageContentType ¶
func WithMessageContentType(contentType string) RouteOption
WithMessageContentType sets the content type for messages Default is "application/json".
func WithMessageExample ¶
func WithMessageExample(direction, name string, example any) RouteOption
WithMessageExample adds a single message example.
func WithMessageExamples ¶
func WithMessageExamples(direction string, examples map[string]any) RouteOption
WithMessageExamples adds message examples for send/receive direction: "send" or "receive" examples: map of example name to example value
func WithMessageHeaders ¶
func WithMessageHeaders(headersSchema any) RouteOption
WithMessageHeaders defines headers schema for messages headersSchema: Go type with header:"name" tags.
func WithMetadata ¶
func WithMetadata(key string, value any) RouteOption
func WithMethod ¶ added in v0.8.0
func WithMethod(method string) RouteOption
WithMethod overrides the HTTP method for a route. Primarily used for SSE/WebSocket endpoints that default to GET.
func WithMiddleware ¶
func WithMiddleware(mw ...Middleware) RouteOption
func WithNoContentResponse ¶
func WithNoContentResponse() RouteOption
WithNoContentResponse creates a 204 No Content response.
func WithOperationID ¶
func WithOperationID(id string) RouteOption
func WithPaginatedResponse ¶
func WithPaginatedResponse(itemType any, statusCode int) RouteOption
WithPaginatedResponse creates a route option for paginated list responses itemType should be a pointer to the item struct type.
func WithParameter ¶
func WithParameter(name, in, description string, required bool, example any) RouteOption
WithParameter adds a parameter definition.
func WithQuerySchema ¶
func WithQuerySchema(schemaType any) RouteOption
WithQuerySchema sets the query parameters schema for OpenAPI generation schemaType should be a struct with query tags.
func WithRequestBody ¶
func WithRequestBody(description string, required bool, example any) RouteOption
WithRequestBody adds request body documentation.
func WithRequestBodySchema ¶
func WithRequestBodySchema(schemaOrType any) RouteOption
WithRequestBodySchema sets only the request body schema for OpenAPI generation Use this for explicit body-only schemas, or when you need separate schemas for different parts of the request. schemaOrType can be either: - A pointer to a struct instance for automatic schema generation - A *Schema for manual schema specification.
func WithRequestContentTypes ¶
func WithRequestContentTypes(types ...string) RouteOption
WithRequestContentTypes specifies the content types for request body.
func WithRequestExample ¶
func WithRequestExample(name string, example any) RouteOption
WithRequestExample adds an example for the request body.
func WithRequestSchema ¶
func WithRequestSchema(schemaOrType any) RouteOption
WithRequestSchema sets the unified request schema for OpenAPI generation This is the recommended approach for new code.
The struct fields are classified 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 with existing code.
func WithRequiredAuth ¶
func WithRequiredAuth(providerName string, scopes ...string) RouteOption
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 WithResponse ¶
func WithResponse(code int, description string, example any) RouteOption
WithResponse adds a response definition to the route.
func WithResponseContentTypes ¶
func WithResponseContentTypes(types ...string) RouteOption
WithResponseContentTypes specifies the content types for response body.
func WithResponseExample ¶
func WithResponseExample(statusCode int, name string, example any) RouteOption
WithResponseExample adds an example for a specific response status code.
func WithResponseSchema ¶
func WithResponseSchema(statusCode int, description string, schemaOrType any) RouteOption
WithResponseSchema sets the response schema for OpenAPI generation statusCode is the HTTP status code (e.g., 200, 201) schemaOrType can be either: - A pointer to a struct instance for automatic schema generation - A *Schema for manual schema specification.
func WithSSEMessage ¶
func WithSSEMessage(eventName string, schema any) RouteOption
WithSSEMessage defines a single message schema for SSE endpoints eventName: the SSE event name (e.g., "message", "update", "notification") schema: the message schema
func WithSSEMessages ¶
func WithSSEMessages(messageSchemas map[string]any) RouteOption
WithSSEMessages defines message schemas for SSE endpoints messageSchemas: map of event names to their schemas SSE is receive-only (server -> client), so action is always "receive".
func WithSchemaRef ¶
func WithSchemaRef(name string, schema any) RouteOption
WithSchemaRef adds a schema reference to components.
func WithSecurity ¶
func WithSecurity(schemes ...string) RouteOption
WithSecurity sets security requirements for a route.
func WithSensitiveFieldCleaning ¶ added in v0.7.0
func WithSensitiveFieldCleaning() RouteOption
WithSensitiveFieldCleaning enables cleaning of sensitive fields in responses. Fields marked with the `sensitive` tag will be processed:
- sensitive:"true" -> set to zero value
- sensitive:"redact" -> set to "[REDACTED]"
- sensitive:"mask:***" -> set to custom mask "***"
func WithServerProtocol ¶
func WithServerProtocol(serverNames ...string) RouteOption
WithServerProtocol specifies which servers this operation should be available on serverNames: list of server names from AsyncAPIConfig.Servers.
func WithSkipInterceptor ¶ added in v0.7.0
func WithSkipInterceptor(names ...string) RouteOption
WithSkipInterceptor skips named interceptors for this route. Useful for excluding specific group-level interceptors. Only named interceptors (created with NewInterceptor) can be skipped.
Example:
adminAPI := router.Group("/admin",
forge.WithGroupInterceptor(RequireAdmin),
)
// Skip admin check for health endpoint
adminAPI.GET("/health", healthHandler,
forge.WithSkipInterceptor("require-admin"),
)
func WithStandardRESTResponses ¶
func WithStandardRESTResponses(resourceType any) RouteOption
WithStandardRESTResponses adds standard REST CRUD responses for a resource Includes 200 (GET/list), 201 (POST), 204 (DELETE), 400, 404, 500.
func WithStrictValidation ¶
func WithStrictValidation() RouteOption
WithStrictValidation enables strict validation (validates both request and response).
func WithSummary ¶
func WithSummary(summary string) RouteOption
func WithTags ¶
func WithTags(tags ...string) RouteOption
func WithTimeout ¶
func WithTimeout(d time.Duration) RouteOption
func WithValidation ¶
func WithValidation(enabled bool) RouteOption
WithValidation adds validation middleware to a route.
func WithValidationErrorResponse ¶
func WithValidationErrorResponse() RouteOption
WithValidationErrorResponse adds a 422 Unprocessable Entity response for validation errors.
func WithWebSocketMessages ¶
func WithWebSocketMessages(sendSchema, receiveSchema any) RouteOption
WithWebSocketMessages defines send/receive message schemas for WebSocket endpoints sendSchema: messages that the client sends to the server (action: send) receiveSchema: messages that the server sends to the client (action: receive).
func WithWebTransport ¶
func WithWebTransport(config WebTransportConfig) RouteOption
WithWebTransport enables WebTransport support with the given configuration.
func WithWebTransportDatagrams ¶
func WithWebTransportDatagrams(enabled bool) RouteOption
WithWebTransportDatagrams enables datagram support for WebTransport.
func WithWebTransportStreams ¶
func WithWebTransportStreams(maxBidi, maxUni int64) RouteOption
WithWebTransportStreams sets the maximum number of streams.
func WithWebhook ¶
func WithWebhook(name string, operation *CallbackOperation) RouteOption
WithWebhook adds a webhook definition to the OpenAPI spec Webhooks are documented at the API level, not per-route.
type Router ¶
type Router interface {
// HTTP Methods - register routes
GET(path string, handler any, opts ...RouteOption) error
POST(path string, handler any, opts ...RouteOption) error
PUT(path string, handler any, opts ...RouteOption) error
DELETE(path string, handler any, opts ...RouteOption) error
PATCH(path string, handler any, opts ...RouteOption) error
OPTIONS(path string, handler any, opts ...RouteOption) error
HEAD(path string, handler any, opts ...RouteOption) error
// Grouping - organize routes
Group(prefix string, opts ...GroupOption) Router
// Middleware - wrap handlers
Use(middleware ...Middleware)
UseGlobal(middleware ...Middleware)
// Controller registration
RegisterController(controller Controller) error
// Lifecycle
Start(ctx context.Context) error
Stop(ctx context.Context) error
// HTTP serving
ServeHTTP(w http.ResponseWriter, r *http.Request)
Handler() http.Handler
// Inspection
Routes() []RouteInfo
RouteByName(name string) (RouteInfo, bool)
RoutesByTag(tag string) []RouteInfo
RoutesByMetadata(key string, value any) []RouteInfo
// OpenAPI
OpenAPISpec() *OpenAPISpec
// AsyncAPI
AsyncAPISpec() *AsyncAPISpec
// Streaming
WebSocket(path string, handler WebSocketHandler, opts ...RouteOption) error
EventStream(path string, handler SSEHandler, opts ...RouteOption) error
SSE(path string, handler Handler, opts ...RouteOption) error
// WebTransport
WebTransport(path string, handler WebTransportHandler, opts ...RouteOption) error
EnableWebTransport(config WebTransportConfig) error
StartHTTP3(addr string, tlsConfig *tls.Config) error
StopHTTP3() error
}
Router provides HTTP routing with multiple backend support.
func GetRouter ¶ added in v0.5.0
GetRouter resolves the router from the container This is a convenience function for resolving the router service.
func NewRouter ¶
func NewRouter(opts ...RouterOption) Router
NewRouter creates a new router with options.
type RouterAdapter ¶
type RouterAdapter = shared.RouterAdapter
RouterAdapter wraps a routing backend.
func NewBunRouterAdapter ¶
func NewBunRouterAdapter() RouterAdapter
NewBunRouterAdapter creates a BunRouter adapter (default).
type RouterOption ¶
type RouterOption interface {
Apply(*routerConfig)
}
RouterOption configures the router.
func WithAsyncAPI ¶
func WithAsyncAPI(config AsyncAPIConfig) RouterOption
WithAsyncAPI enables AsyncAPI 3.0.0 spec generation.
func WithContainer ¶
func WithContainer(container di.Container) RouterOption
func WithErrorHandler ¶
func WithErrorHandler(handler ErrorHandler) RouterOption
func WithHealth ¶
func WithHealth(config shared.HealthConfig) RouterOption
WithHealth enables health checks.
func WithLogger ¶
func WithLogger(logger Logger) RouterOption
func WithMetrics ¶
func WithMetrics(config shared.MetricsConfig) RouterOption
WithMetrics enables metrics collection.
func WithOpenAPI ¶
func WithOpenAPI(config OpenAPIConfig) RouterOption
WithOpenAPI enables OpenAPI 3.1.0 spec generation.
func WithRecovery ¶
func WithRecovery() RouterOption
type SSEHandler ¶
SSEHandler handles Server-Sent Events.
type Schema ¶
Schema represents a JSON Schema (OpenAPI 3.1.0 uses JSON Schema 2020-12).
func GetSchemaFromType ¶
GetSchemaFromType is a helper to get schema from a type.
type SchemaValidator ¶
type SchemaValidator struct {
// contains filtered or unexported fields
}
SchemaValidator validates data against JSON schemas.
func NewSchemaValidator ¶
func NewSchemaValidator() *SchemaValidator
NewSchemaValidator creates a new schema validator.
func (*SchemaValidator) RegisterSchema ¶
func (v *SchemaValidator) RegisterSchema(name string, schema *Schema)
RegisterSchema registers a schema with a name.
func (*SchemaValidator) ValidateRequest ¶
func (v *SchemaValidator) ValidateRequest(schema *Schema, data any) error
ValidateRequest validates request data against a schema.
func (*SchemaValidator) ValidateResponse ¶
func (v *SchemaValidator) ValidateResponse(schema *Schema, data any) error
ValidateResponse validates response data against a schema.
type SecurityRequirement ¶
type SecurityRequirement = shared.SecurityRequirement
SecurityRequirement lists required security schemes.
type SecurityScheme ¶
type SecurityScheme = shared.SecurityScheme
SecurityScheme defines a security scheme.
type Stream ¶
type Stream interface {
// Send sends an event to the stream
Send(event string, data []byte) error
// SendJSON sends JSON event to the stream
SendJSON(event string, v any) error
// Flush flushes any buffered data
Flush() error
// Close closes the stream
Close() error
// Context returns the stream context
Context() context.Context
// SetRetry sets the retry timeout for SSE
SetRetry(milliseconds int) error
// SendComment sends a comment (keeps connection alive)
SendComment(comment string) error
}
Stream represents a Server-Sent Events stream.
type StreamConfig ¶
type StreamConfig struct {
// WebSocket configuration
ReadBufferSize int
WriteBufferSize int
EnableCompression bool
// SSE configuration
RetryInterval int // milliseconds
KeepAlive bool
// WebTransport configuration
EnableWebTransport bool
MaxBidiStreams int64
MaxUniStreams int64
MaxDatagramFrameSize int64
EnableDatagrams bool
StreamReceiveWindow uint64
ConnectionReceiveWindow uint64
WebTransportKeepAlive int // milliseconds
WebTransportMaxIdle int // milliseconds
}
StreamConfig configures streaming behavior.
func DefaultStreamConfig ¶
func DefaultStreamConfig() StreamConfig
DefaultStreamConfig returns default streaming configuration.
type ValidationError ¶
type ValidationError = shared.ValidationError
Re-export validation types from shared to maintain backward compatibility
type ValidationErrorResponse ¶
type ValidationErrorResponse = shared.ValidationErrorResponse
type ValidationErrors ¶
type ValidationErrors = shared.ValidationErrors
type WebSocketChannelBinding ¶
type WebSocketChannelBinding = shared.WebSocketChannelBinding
Type aliases for AsyncAPI types.
type WebSocketHandler ¶
type WebSocketHandler func(ctx Context, conn Connection) error
WebSocketHandler handles WebSocket connections.
type WebTransportConfig ¶
type WebTransportConfig struct {
// Maximum bidirectional streams
MaxBidiStreams int64
// Maximum unidirectional streams
MaxUniStreams int64
// Maximum datagram frame size
MaxDatagramFrameSize int64
// Enable datagram support
EnableDatagrams bool
// Stream receive window
StreamReceiveWindow uint64
// Connection receive window
ConnectionReceiveWindow uint64
// Keep alive interval
KeepAliveInterval int // milliseconds
// Max idle timeout
MaxIdleTimeout int // milliseconds
}
WebTransportConfig configures WebTransport behavior.
func DefaultWebTransportConfig ¶
func DefaultWebTransportConfig() WebTransportConfig
DefaultWebTransportConfig returns default WebTransport configuration.
type WebTransportHandler ¶
type WebTransportHandler func(ctx Context, session WebTransportSession) error
WebTransportHandler handles WebTransport sessions.
type WebTransportSession ¶
type WebTransportSession interface {
// ID returns unique session ID
ID() string
// OpenStream opens a new bidirectional stream
OpenStream() (WebTransportStream, error)
// OpenUniStream opens a new unidirectional stream
OpenUniStream() (WebTransportStream, error)
// AcceptStream accepts an incoming bidirectional stream
AcceptStream(ctx context.Context) (WebTransportStream, error)
// AcceptUniStream accepts an incoming unidirectional stream
AcceptUniStream(ctx context.Context) (WebTransportStream, error)
// ReceiveDatagram receives a datagram
ReceiveDatagram(ctx context.Context) ([]byte, error)
// SendDatagram sends a datagram
SendDatagram(data []byte) error
// Close closes the session
Close() error
// Context returns the session context
Context() context.Context
// RemoteAddr returns the remote address
RemoteAddr() string
// LocalAddr returns the local address
LocalAddr() string
}
WebTransportSession represents a WebTransport session.
type WebTransportStream ¶
type WebTransportStream interface {
io.ReadWriteCloser
// StreamID returns the stream ID
StreamID() uint64
// Read reads data from the stream
Read(p []byte) (n int, err error)
// Write writes data to the stream
Write(p []byte) (n int, err error)
// ReadJSON reads JSON from the stream
ReadJSON(v any) error
// WriteJSON writes JSON to the stream
WriteJSON(v any) error
// Close closes the stream
Close() error
}
WebTransportStream represents a WebTransport stream.
Source Files
¶
- asyncapi_generator.go
- asyncapi_schema.go
- bunrouter.go
- controller.go
- handler.go
- helpers.go
- interceptor.go
- interceptor_combinators.go
- interceptor_executor.go
- interceptor_opts.go
- interceptor_parallel.go
- interceptors.go
- middleware.go
- openapi.go
- openapi_callbacks.go
- openapi_generator.go
- openapi_params.go
- openapi_request_schema.go
- openapi_response_schema.go
- openapi_responses.go
- openapi_schema.go
- router.go
- router_asyncapi.go
- router_asyncapi_opts.go
- router_auth_opts.go
- router_impl.go
- router_observability.go
- router_openapi.go
- router_openapi_opts.go
- router_opts.go
- router_streaming.go
- router_webtransport.go
- router_webtransport_opts.go
- streaming.go
- streaming_sse.go
- streaming_websocket.go
- types.go
- validation.go
- validation_errors.go
- webtransport.go