router

package
v0.6.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 19, 2025 License: Apache-2.0 Imports: 26 Imported by: 0

Documentation

Index

Constants

View Source
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

View Source
const ManagerKey = shared.RouterKey

ManagerKey is the DI key for the router service.

View Source
const ParamsContextKey = "forge:params"

ParamsContextKey is used to store route params in request context Exported so di.NewContext can use the same key.

Variables

View Source
var (
	NewHTTPError  = errors.NewHTTPError
	BadRequest    = errors.BadRequest
	Unauthorized  = errors.Unauthorized
	Forbidden     = errors.Forbidden
	NotFound      = errors.NotFound
	InternalError = errors.InternalError
)
View Source
var (
	NewValidationErrors        = shared.NewValidationErrors
	NewValidationErrorResponse = shared.NewValidationErrorResponse
)

Re-export validation functions

Functions

func FormatValidationError

func FormatValidationError(err error) (int, []byte)

FormatValidationError formats validation errors for HTTP response.

func GetTypeName

func GetTypeName(t reflect.Type) string

GetTypeName returns a qualified type name for schema references.

func ValidateQueryParams

func ValidateQueryParams(r *http.Request, schemaType any) error

ValidateQueryParams validates query parameters against a struct schema.

func ValidateRequestBody

func ValidateRequestBody(r *http.Request, schema *Schema) error

ValidateRequestBody validates the request body against a 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 AsyncAPIConfig

type AsyncAPIConfig = shared.AsyncAPIConfig

Type aliases for AsyncAPI types.

type AsyncAPIInfo

type AsyncAPIInfo = shared.AsyncAPIInfo

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 AsyncAPIServer

type AsyncAPIServer = shared.AsyncAPIServer

Type aliases for AsyncAPI types.

type AsyncAPISpec

type AsyncAPISpec = shared.AsyncAPISpec

Type aliases for AsyncAPI types.

type AsyncAPITag

type AsyncAPITag = shared.AsyncAPITag

Type aliases for AsyncAPI types.

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 Contact

type Contact = shared.Contact

Contact represents contact information.

type Context

type Context = shared.Context

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 Discriminator

type Discriminator = shared.Discriminator

Discriminator supports polymorphism.

type DiscriminatorConfig

type DiscriminatorConfig struct {
	PropertyName string
	Mapping      map[string]string
}

DiscriminatorConfig defines discriminator for polymorphic types.

type Encoding

type Encoding = shared.Encoding

Encoding defines encoding for a property.

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 Example

type Example = shared.Example

Example provides an example value.

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:

  1. Register(app) - Register services with DI container
  2. Start(ctx) - Start the extension
  3. Health(ctx) - Check extension health (called periodically)
  4. Stop(ctx) - Stop the extension (called during graceful shutdown)

type ExternalDocs

type ExternalDocs = shared.ExternalDocs

ExternalDocs points to external documentation.

type ExternalDocsDef

type ExternalDocsDef struct {
	Description string
	URL         string
}

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 HTTPError

type HTTPError = errors.HTTPError

Re-export HTTP error types and constructors for backward compatibility.

type Handler added in v0.5.0

type Handler func(ctx Context) error

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 Header = shared.Header

Header describes a single header parameter.

type Info

type Info = shared.Info

Info provides metadata about the API.

type License

type License = shared.License

License represents license information.

type Link = shared.Link

Link represents a possible design-time link for a response.

type Logger

type Logger = logger.Logger

type MediaType

type MediaType = shared.MediaType

MediaType provides schema and examples for a media type.

type Middleware

type Middleware func(next Handler) Handler

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

type MiddlewareFunc func(w http.ResponseWriter, r *http.Request, next http.Handler)

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 OAuthFlow

type OAuthFlow = shared.OAuthFlow

OAuthFlow defines a single OAuth 2.0 flow.

type OAuthFlows

type OAuthFlows = shared.OAuthFlows

OAuthFlows defines OAuth 2.0 flows.

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 Operation

type Operation = shared.Operation

Operation describes a single API operation on a path.

type Parameter

type Parameter = shared.Parameter

Parameter describes a single operation parameter.

type ParameterDef

type ParameterDef struct {
	Name        string
	In          string
	Description string
	Required    bool
	Example     any
}

ParameterDef defines a parameter.

type PathItem

type PathItem = shared.PathItem

PathItem describes operations available on a single path.

type PathParam

type PathParam struct {
	Name        string
	Description string
	Schema      *Schema
}

PathParam represents a parsed path parameter.

type PureMiddleware added in v0.5.0

type PureMiddleware func(http.Handler) http.Handler

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

type RequestBodyDef struct {
	Description string
	Required    bool
	Example     any
}

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 Response

type Response = shared.Response

Response describes a single response from an API operation.

type ResponseDef

type ResponseDef struct {
	Description string
	Example     any
}

ResponseDef defines a response.

type ResponseSchemaDef

type ResponseSchemaDef struct {
	Description string
	Schema      any
}

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

type RouteExtension interface {
	Name() string
	Validate() error
}

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 WithName

func WithName(name string) RouteOption

Route option constructors.

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

func GetRouter(container shared.Container) (Router, error)

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 WithAdapter

func WithAdapter(adapter RouterAdapter) RouterOption

Router option constructors.

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

type SSEHandler func(ctx Context, stream Stream) error

SSEHandler handles Server-Sent Events.

type Schema

type Schema = shared.Schema

Schema represents a JSON Schema (OpenAPI 3.1.0 uses JSON Schema 2020-12).

func GetSchemaFromType

func GetSchemaFromType(t reflect.Type) *Schema

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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL