Documentation
¶
Index ¶
- Constants
- Variables
- 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
- 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 ErrorHandler
- type Example
- type Extension
- type ExternalDocs
- type ExternalDocsDef
- type GroupConfig
- type GroupOption
- func WithGroupAuth(providerNames ...string) GroupOption
- func WithGroupAuthAnd(providerNames ...string) GroupOption
- func WithGroupMetadata(key string, value any) GroupOption
- func WithGroupMiddleware(mw ...Middleware) GroupOption
- func WithGroupRequiredScopes(scopes ...string) GroupOption
- func WithGroupTags(tags ...string) GroupOption
- type HTTPChannelBinding
- type HTTPError
- type Handler
- type HandlerPattern
- type Header
- type Info
- 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 RequestBody
- type RequestBodyDef
- type RequestComponents
- type Response
- 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 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 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 WithServerProtocol(serverNames ...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 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 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.
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 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
}
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 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 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 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 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 ResponseDef ¶
ResponseDef defines a response.
type ResponseSchemaDef ¶
ResponseSchemaDef defines a response schema.
type RouteConfig ¶
type RouteConfig struct {
Name string
Summary string
Description string
Tags []string
Middleware []Middleware
Timeout time.Duration
Metadata map[string]any
Extensions map[string]Extension
// OpenAPI metadata
OperationID string
Deprecated 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
}
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 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 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 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 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)
// 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
// 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
- middleware.go
- openapi.go
- openapi_callbacks.go
- openapi_generator.go
- openapi_params.go
- openapi_request_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