Documentation
¶
Index ¶
- Constants
- Variables
- func FormatValidationError(err error) (int, []byte)
- func GetTypeName(t reflect.Type) string
- func ValidateQueryParams(r *http.Request, schemaType interface{}) 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
- func NewCompletionCallbackConfig(callbackURLExpression string, resultSchema interface{}) CallbackConfig
- func NewEventCallbackConfig(callbackURLExpression string, eventSchema interface{}) CallbackConfig
- func NewStatusCallbackConfig(callbackURLExpression string, statusSchema interface{}) 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 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 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 interface{}) 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 interface{}, statusCode int) RouteOption
- func WithCallback(config CallbackConfig) RouteOption
- func WithCorrelationID(location, description string) RouteOption
- func WithCreatedResponse(resourceType interface{}) 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 interface{}) RouteOption
- func WithListResponse(itemType interface{}, statusCode int) RouteOption
- func WithMessageContentType(contentType string) RouteOption
- func WithMessageExample(direction, name string, example interface{}) RouteOption
- func WithMessageExamples(direction string, examples map[string]interface{}) RouteOption
- func WithMessageHeaders(headersSchema interface{}) 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 interface{}, statusCode int) RouteOption
- func WithParameter(name, in, description string, required bool, example interface{}) RouteOption
- func WithQuerySchema(schemaType interface{}) RouteOption
- func WithRequestBody(description string, required bool, example interface{}) RouteOption
- func WithRequestBodySchema(schemaOrType interface{}) RouteOption
- func WithRequestContentTypes(types ...string) RouteOption
- func WithRequestExample(name string, example interface{}) RouteOption
- func WithRequestSchema(schemaOrType interface{}) RouteOption
- func WithRequiredAuth(providerName string, scopes ...string) RouteOption
- func WithResponse(code int, description string, example interface{}) RouteOption
- func WithResponseContentTypes(types ...string) RouteOption
- func WithResponseExample(statusCode int, name string, example interface{}) RouteOption
- func WithResponseSchema(statusCode int, description string, schemaOrType interface{}) RouteOption
- func WithSSEMessage(eventName string, schema interface{}) RouteOption
- func WithSSEMessages(messageSchemas map[string]interface{}) RouteOption
- func WithSchemaRef(name string, schema interface{}) RouteOption
- func WithSecurity(schemes ...string) RouteOption
- func WithServerProtocol(serverNames ...string) RouteOption
- func WithStandardRESTResponses(resourceType interface{}) 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 interface{}) 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
- func (ve *ValidationErrors) Add(field, message string, value interface{})
- func (ve *ValidationErrors) AddWithCode(field, message, code string, value interface{})
- func (ve *ValidationErrors) Count() int
- func (ve *ValidationErrors) Error() string
- func (ve *ValidationErrors) HasErrors() bool
- func (ve *ValidationErrors) ToJSON() ([]byte, error)
- type WebSocketChannelBinding
- type WebSocketHandler
- type WebTransportConfig
- type WebTransportHandler
- type WebTransportSession
- type WebTransportStream
Constants ¶
const ( ErrCodeRequired = "REQUIRED" ErrCodeInvalidType = "INVALID_TYPE" ErrCodeInvalidFormat = "INVALID_FORMAT" ErrCodeMinLength = "MIN_LENGTH" ErrCodeMaxLength = "MAX_LENGTH" ErrCodeMinValue = "MIN_VALUE" ErrCodeMaxValue = "MAX_VALUE" ErrCodePattern = "PATTERN" ErrCodeEnum = "ENUM" ErrCodeMinItems = "MIN_ITEMS" ErrCodeMaxItems = "MAX_ITEMS" ErrCodeUniqueItems = "UNIQUE_ITEMS" )
Common validation error codes
Variables ¶
var ( NewHTTPError = errors.NewHTTPError BadRequest = errors.BadRequest Forbidden = errors.Forbidden NotFound = errors.NotFound InternalError = errors.InternalError )
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) 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 interface{}) CallbackConfig
NewCompletionCallbackConfig creates a callback config for async operation completion
func NewEventCallbackConfig ¶
func NewEventCallbackConfig(callbackURLExpression string, eventSchema interface{}) CallbackConfig
NewEventCallbackConfig creates a callback config for event notifications
func NewStatusCallbackConfig ¶
func NewStatusCallbackConfig(callbackURLExpression string, statusSchema interface{}) 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 interface{}) *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 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 HTTP handlers
func Chain ¶
func Chain(middlewares ...Middleware) Middleware
Chain combines multiple middleware into a single middleware Middleware are applied in the order they are provided
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
func (MiddlewareFunc) ToMiddleware ¶
func (f MiddlewareFunc) ToMiddleware() Middleware
ToMiddleware converts a MiddlewareFunc to a Middleware
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 ¶
type ParameterDef struct {
Name string
In string
Description string
Required bool
Example interface{}
}
ParameterDef defines a parameter
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 ¶
type ResponseDef struct {
Description string
Example interface{}
}
ResponseDef defines a response
type ResponseSchemaDef ¶
type ResponseSchemaDef struct {
Description string
Schema interface{}
}
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 interface{}) 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 interface{}, 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 interface{}) 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 interface{}) RouteOption
WithHeaderSchema sets the header parameters schema for OpenAPI generation schemaType should be a struct with header tags
func WithListResponse ¶
func WithListResponse(itemType interface{}, 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 interface{}) RouteOption
WithMessageExample adds a single message example
func WithMessageExamples ¶
func WithMessageExamples(direction string, examples map[string]interface{}) 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 interface{}) 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 interface{}, 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 interface{}) RouteOption
WithParameter adds a parameter definition
func WithQuerySchema ¶
func WithQuerySchema(schemaType interface{}) 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 interface{}) RouteOption
WithRequestBody adds request body documentation
func WithRequestBodySchema ¶
func WithRequestBodySchema(schemaOrType interface{}) 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 interface{}) RouteOption
WithRequestExample adds an example for the request body
func WithRequestSchema ¶
func WithRequestSchema(schemaOrType interface{}) 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 interface{}) 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 interface{}) RouteOption
WithResponseExample adds an example for a specific response status code
func WithResponseSchema ¶
func WithResponseSchema(statusCode int, description string, schemaOrType interface{}) 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 interface{}) 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]interface{}) 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 interface{}) 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 interface{}) 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 interface{}) 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 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 interface{}) error
ValidateRequest validates request data against a schema
func (*SchemaValidator) ValidateResponse ¶
func (v *SchemaValidator) ValidateResponse(schema *Schema, data interface{}) 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 struct {
Field string `json:"field"`
Message string `json:"message"`
Value interface{} `json:"value,omitempty"`
Code string `json:"code,omitempty"`
}
ValidationError represents a single field validation error
type ValidationErrorResponse ¶
type ValidationErrorResponse struct {
Error string `json:"error"`
Code int `json:"code"`
ValidationErrors []ValidationError `json:"validationErrors"`
}
ValidationErrorResponse is the HTTP response for validation errors
func NewValidationErrorResponse ¶
func NewValidationErrorResponse(errors *ValidationErrors) *ValidationErrorResponse
NewValidationErrorResponse creates a new validation error response
type ValidationErrors ¶
type ValidationErrors struct {
Errors []ValidationError `json:"errors"`
}
ValidationErrors is a collection of validation errors
func NewValidationErrors ¶
func NewValidationErrors() *ValidationErrors
NewValidationErrors creates a new ValidationErrors instance
func (*ValidationErrors) Add ¶
func (ve *ValidationErrors) Add(field, message string, value interface{})
Add adds a validation error
func (*ValidationErrors) AddWithCode ¶
func (ve *ValidationErrors) AddWithCode(field, message, code string, value interface{})
AddWithCode adds a validation error with a code
func (*ValidationErrors) Count ¶
func (ve *ValidationErrors) Count() int
Count returns the number of validation errors
func (*ValidationErrors) Error ¶
func (ve *ValidationErrors) Error() string
Error implements the error interface
func (*ValidationErrors) HasErrors ¶
func (ve *ValidationErrors) HasErrors() bool
HasErrors returns true if there are validation errors
func (*ValidationErrors) ToJSON ¶
func (ve *ValidationErrors) ToJSON() ([]byte, error)
ToJSON converts validation errors to JSON bytes
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
- 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