router

package
v0.8.6 Latest Latest
Warning

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

Go to latest
Published: Jan 3, 2026 License: Apache-2.0 Imports: 27 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 (
	// ContextKeySensitiveFieldCleaning is the context key for sensitive field cleaning flag.
	ContextKeySensitiveFieldCleaning = "forge:sensitive_field_cleaning"
)

Context keys for internal use.

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 ConvertPathToOpenAPIFormat added in v0.7.0

func ConvertPathToOpenAPIFormat(path string) string

ConvertPathToOpenAPIFormat converts a path with :param style parameters to OpenAPI's {param} style format. e.g., /api/workspaces/:workspace_id/users -> /api/workspaces/{workspace_id}/users

func FormatValidationError

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.

func (*BunRouterAdapter) UseGlobal added in v0.7.0

func (a *BunRouterAdapter) UseGlobal(middleware func(http.Handler) http.Handler)

UseGlobal registers global middleware that runs before routing. This middleware will run for ALL requests, even those that don't match any route. This is critical for CORS preflight handling.

type CallbackConfig

type CallbackConfig struct {
	Name       string
	Expression string // Callback URL expression (e.g., "{$request.body#/callbackUrl}")
	Operations map[string]*CallbackOperation
}

CallbackConfig defines a callback (webhook) for an operation.

func NewCompletionCallbackConfig

func NewCompletionCallbackConfig(callbackURLExpression string, resultSchema any) CallbackConfig

NewCompletionCallbackConfig creates a callback config for async operation completion.

func NewEventCallbackConfig

func NewEventCallbackConfig(callbackURLExpression string, eventSchema any) CallbackConfig

NewEventCallbackConfig creates a callback config for event notifications.

func NewStatusCallbackConfig

func NewStatusCallbackConfig(callbackURLExpression string, statusSchema any) CallbackConfig

NewStatusCallbackConfig creates a callback config for status updates.

type CallbackOperation

type CallbackOperation struct {
	Summary     string
	Description string
	RequestBody *RequestBody
	Responses   map[string]*Response
}

CallbackOperation defines an operation that will be called back.

func NewCallbackOperation

func NewCallbackOperation(summary, description string) *CallbackOperation

NewCallbackOperation creates a new callback operation.

func (*CallbackOperation) WithCallbackRequestBody

func (co *CallbackOperation) WithCallbackRequestBody(description string, schema any) *CallbackOperation

WithCallbackRequestBody sets the request body for a callback operation.

func (*CallbackOperation) WithCallbackResponse

func (co *CallbackOperation) WithCallbackResponse(statusCode int, description string) *CallbackOperation

WithCallbackResponse adds a response to a callback operation.

type Components

type Components = shared.Components

Components holds reusable objects for the API spec.

type Connection

type Connection interface {
	// ID returns unique connection ID
	ID() string

	// Read reads a message from the connection
	Read() ([]byte, error)

	// ReadJSON reads JSON from the connection
	ReadJSON(v any) error

	// Write sends a message to the connection
	Write(data []byte) error

	// WriteJSON sends JSON to the connection
	WriteJSON(v any) error

	// Close closes the connection
	Close() error

	// Context returns the connection context
	Context() context.Context

	// RemoteAddr returns the remote address
	RemoteAddr() string

	// LocalAddr returns the local address
	LocalAddr() string
}

Connection represents a WebSocket connection.

type 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 EnumNamer added in v0.7.0

type EnumNamer = shared.EnumNamer

EnumNamer is an optional interface that enum types can implement to provide a custom component name in the OpenAPI schema.

type EnumValuer added in v0.7.0

type EnumValuer = shared.EnumValuer

EnumValuer is an optional interface that enum types can implement to provide their possible values for OpenAPI schema generation.

type ErrorHandler

type ErrorHandler = shared.ErrorHandler

ErrorHandler handles errors from handlers.

func NewDefaultErrorHandler

func NewDefaultErrorHandler(l Logger) ErrorHandler

NewDefaultErrorHandler creates a default error handler.

type 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

	// Interceptors inherited by all routes in the group
	Interceptors     []Interceptor
	SkipInterceptors map[string]bool // Names of interceptors to skip
}

GroupConfig holds route group configuration.

type GroupOption

type GroupOption interface {
	Apply(*GroupConfig)
}

GroupOption configures a route group.

func WithGroupAuth

func WithGroupAuth(providerNames ...string) GroupOption

WithGroupAuth adds authentication to all routes in a group. Multiple providers create an OR condition.

Example:

api := router.Group("/api", forge.WithGroupAuth("jwt"))

func WithGroupAuthAnd

func WithGroupAuthAnd(providerNames ...string) GroupOption

WithGroupAuthAnd requires all providers to succeed for all routes in the group.

func WithGroupInterceptor added in v0.7.0

func WithGroupInterceptor(interceptors ...Interceptor) GroupOption

WithGroupInterceptor adds interceptors to all routes in a group. Group interceptors run before route-specific interceptors. These interceptors are inherited by nested groups.

Example:

adminAPI := router.Group("/admin",
    forge.WithGroupInterceptor(RequireAuth(), RequireAdmin),
)

// All routes in this group require auth and admin role
adminAPI.GET("/users", listUsers)
adminAPI.DELETE("/users/:id", deleteUser)

func WithGroupMetadata

func WithGroupMetadata(key string, value any) GroupOption

func WithGroupMiddleware

func WithGroupMiddleware(mw ...Middleware) GroupOption

Group option constructors.

func WithGroupRequiredScopes

func WithGroupRequiredScopes(scopes ...string) GroupOption

WithGroupRequiredScopes sets required scopes for all routes in a group.

func WithGroupSkipInterceptor added in v0.7.0

func WithGroupSkipInterceptor(names ...string) GroupOption

WithGroupSkipInterceptor skips named interceptors for all routes in a group. Useful for excluding parent group interceptors from a nested group.

Example:

api := router.Group("/api",
    forge.WithGroupInterceptor(RateLimitInterceptor),
)

// Nested group without rate limiting
internal := api.Group("/internal",
    forge.WithGroupSkipInterceptor("rate-limit"),
)

func WithGroupTags

func WithGroupTags(tags ...string) GroupOption

type HTTPChannelBinding

type HTTPChannelBinding = shared.HTTPChannelBinding

Type aliases for AsyncAPI types.

type 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 Interceptor added in v0.7.0

type Interceptor interface {
	// Name returns the unique identifier for this interceptor.
	// Used for skipping, debugging, and logging.
	Name() string

	// Intercept executes the interceptor logic.
	Intercept(ctx Context, route RouteInfo) InterceptorResult
}

Interceptor represents a named interceptor with metadata. Named interceptors can be skipped on specific routes.

func AllowIPs added in v0.7.0

func AllowIPs(allowedIPs ...string) Interceptor

AllowIPs creates an interceptor that only allows specific IP addresses.

func And added in v0.7.0

func And(interceptors ...Interceptor) Interceptor

And combines interceptors sequentially - ALL must pass. Executes in order, short-circuits on first block. Values from all interceptors are merged into context as they complete.

Example:

router.POST("/admin/users", handler,
    forge.WithInterceptor(
        And(RequireAuth(), RequireRole("admin"), RequireScopes("write:users")),
    ),
)

func AuditLog added in v0.7.0

func AuditLog(logger func(ctx Context, route RouteInfo, timestamp time.Time)) Interceptor

AuditLog creates an interceptor that logs access attempts. The logger function is called with audit information.

func ChainInterceptors added in v0.7.0

func ChainInterceptors(interceptors ...Interceptor) Interceptor

ChainInterceptors combines multiple interceptors into a single interceptor. All interceptors are executed in order; all must pass. This is equivalent to And() but more explicit about sequential execution.

func DenyIPs added in v0.7.0

func DenyIPs(deniedIPs ...string) Interceptor

DenyIPs creates an interceptor that blocks specific IP addresses.

func Enrich added in v0.7.0

func Enrich(name string, loader func(ctx Context, route RouteInfo) (map[string]any, error)) Interceptor

Enrich creates an interceptor that enriches the context with values. The loader function is called to fetch data to inject.

func EnrichFromService added in v0.7.0

func EnrichFromService[T any](serviceName string, loader func(ctx Context, svc T) (map[string]any, error)) Interceptor

EnrichFromService creates an interceptor that loads data from a DI service.

func EnrichUser added in v0.7.0

func EnrichUser(loader func(ctx Context) (any, error)) Interceptor

EnrichUser creates an interceptor that loads user data into context under "user" key.

func FeatureFlag added in v0.7.0

func FeatureFlag(flagName string, checker func(ctx Context, flag string) bool) Interceptor

FeatureFlag creates an interceptor that checks if a feature is enabled. The checker function determines if the feature is enabled for the current request.

func FeatureFlagFromContext added in v0.7.0

func FeatureFlagFromContext(flagName string) Interceptor

FeatureFlagFromContext creates an interceptor that checks a feature flag from context. Expects a "feature-flags" map[string]bool in context.

func FromFunc added in v0.7.0

func FromFunc(fn InterceptorFunc) Interceptor

FromFunc creates an anonymous interceptor from a simple function. Equivalent to InterceptorFromFunc but with a clearer name.

func IfMetadata added in v0.7.0

func IfMetadata(key string, expectedValue any, interceptor Interceptor) Interceptor

IfMetadata conditionally executes an interceptor based on route metadata. If the metadata key doesn't exist or doesn't match the expected value, skips the interceptor.

Example:

// Only run rate limiting on routes marked for it
router.GET("/api/data", handler,
    forge.WithMetadata("rate-limit", true),
    forge.WithInterceptor(
        IfMetadata("rate-limit", true, RateLimitInterceptor),
    ),
)

func IfTag added in v0.7.0

func IfTag(tag string, interceptor Interceptor) Interceptor

IfTag conditionally executes an interceptor based on route tags. If the route doesn't have the specified tag, skips the interceptor.

Example:

// Only audit routes tagged as "sensitive"
router.POST("/api/payment", handler,
    forge.WithTags("sensitive"),
    forge.WithInterceptor(
        IfTag("sensitive", AuditLogInterceptor),
    ),
)

func InterceptorFromFunc added in v0.7.0

func InterceptorFromFunc(fn InterceptorFunc) Interceptor

InterceptorFromFunc creates an anonymous interceptor from a function. Anonymous interceptors cannot be skipped by name. Use NewInterceptor for interceptors that may need to be skipped.

func Maintenance added in v0.7.0

func Maintenance(checker func() bool) Interceptor

Maintenance creates an interceptor that blocks requests during maintenance. The checker function returns true if maintenance mode is active.

func Named added in v0.7.0

func Named(name string, interceptor Interceptor) Interceptor

Named wraps an anonymous interceptor with a name. Useful for making interceptors skippable.

func NewInterceptor added in v0.7.0

func NewInterceptor(name string, fn InterceptorFunc) Interceptor

NewInterceptor creates a named interceptor from a function. Named interceptors can be skipped using WithSkipInterceptor.

Example:

var RequireAdmin = NewInterceptor("require-admin", func(ctx Context, route RouteInfo) InterceptorResult {
    if ctx.Get("user.role") != "admin" {
        return Block(Forbidden("admin access required"))
    }
    return Allow()
})

func Not added in v0.7.0

func Not(interceptor Interceptor, blockError error) Interceptor

Not inverts an interceptor's decision. If the interceptor blocks, Not allows. If it allows, Not blocks with the provided error.

Example:

// Block if user IS an admin (inverse check)
var BlockAdmins = Not(RequireRole("admin"), Forbidden("admins cannot access this"))

func Or added in v0.7.0

func Or(interceptors ...Interceptor) Interceptor

Or combines interceptors sequentially - ANY one passing is sufficient. Executes in order, short-circuits on first success.

Example:

router.GET("/api/data", handler,
    forge.WithInterceptor(
        Or(RequireAuth(), RequireAPIKey()),
    ),
)

func Parallel added in v0.7.0

func Parallel(interceptors ...Interceptor) Interceptor

Parallel executes interceptors concurrently and collects results. ALL interceptors must pass for the request to proceed. If any interceptor blocks, the first blocking error is returned. Values from all passing interceptors are merged.

Example:

// Load user data concurrently
router.GET("/dashboard", handler,
    forge.WithInterceptor(
        Parallel(
            EnrichUser(loadUser),
            Enrich("prefs", loadPreferences),
            Enrich("notifications", loadNotifications),
        ),
    ),
)

func ParallelAny added in v0.7.0

func ParallelAny(interceptors ...Interceptor) Interceptor

ParallelAny executes interceptors concurrently. ANY one passing is sufficient to proceed. Returns as soon as one interceptor allows. This is useful for "any of these auth methods" scenarios.

Example:

// Any authentication method works
router.GET("/api/data", handler,
    forge.WithInterceptor(
        ParallelAny(
            RequireAuthProvider("jwt"),
            RequireAuthProvider("api-key"),
            RequireAuthProvider("oauth2"),
        ),
    ),
)

func RateLimit added in v0.7.0

func RateLimit(keyName string, checker func(ctx Context, key string) RateLimitResult) Interceptor

RateLimit creates a rate limit interceptor. The checker function should return the rate limit status for the given key. Rate limit info is added to context for response headers.

func RateLimitByIP added in v0.7.0

func RateLimitByIP(checker func(ctx Context, ip string) RateLimitResult) Interceptor

RateLimitByIP creates a rate limit interceptor keyed by client IP.

func RequireAllRoles added in v0.7.0

func RequireAllRoles(roles ...string) Interceptor

RequireAllRoles creates an interceptor that requires ALL specified roles. Checks the "user.roles" context value (expected to be []string).

func RequireAnyScope added in v0.7.0

func RequireAnyScope(scopes ...string) Interceptor

RequireAnyScope creates an interceptor that requires ANY of the specified scopes. At least one scope must be present.

func RequireAuth added in v0.7.0

func RequireAuth() Interceptor

RequireAuth creates an interceptor that requires authentication. Checks for "auth" or "user" in the context (typically set by auth middleware).

func RequireAuthProvider added in v0.7.0

func RequireAuthProvider(providerName string) Interceptor

RequireAuthProvider creates an interceptor that requires a specific auth provider. Checks the "auth.provider" context value.

func RequireContentType added in v0.7.0

func RequireContentType(contentTypes ...string) Interceptor

RequireContentType creates an interceptor that requires a specific Content-Type.

func RequireHeader added in v0.7.0

func RequireHeader(headers ...string) Interceptor

RequireHeader creates an interceptor that requires specific headers to be present.

func RequireMetadata added in v0.7.0

func RequireMetadata(key string, expectedValue any) Interceptor

RequireMetadata creates an interceptor that checks route metadata.

func RequireRole added in v0.7.0

func RequireRole(roles ...string) Interceptor

RequireRole creates an interceptor that requires ANY of the specified roles. Checks the "user.role" context value.

func RequireScopes added in v0.7.0

func RequireScopes(scopes ...string) Interceptor

RequireScopes creates an interceptor that requires ALL specified scopes. Checks the "auth.scopes" context value (expected to be []string).

func RequireTag added in v0.7.0

func RequireTag(tag string) Interceptor

RequireTag creates an interceptor that checks if route has a specific tag.

func TenantIsolation added in v0.7.0

func TenantIsolation(tenantParamName string) Interceptor

TenantIsolation creates an interceptor that validates tenant access. Compares the tenant from the URL param with the user's tenant.

func TimeWindow added in v0.7.0

func TimeWindow(startHour, endHour int, location *time.Location) Interceptor

TimeWindow creates an interceptor that only allows requests during specific hours. Hours are in 24-hour format (0-23) in the specified timezone.

func Unless added in v0.7.0

func Unless(predicate func(ctx Context, route RouteInfo) bool, interceptor Interceptor) Interceptor

Unless conditionally skips an interceptor based on a predicate. If the predicate returns true, the interceptor is skipped (allows). This is the inverse of When.

Example:

// Skip auth for requests with valid API key header
router.GET("/api/data", handler,
    forge.WithInterceptor(
        Unless(func(ctx Context, route RouteInfo) bool {
            return ctx.Header("X-API-Key") != ""
        }, RequireAuth()),
    ),
)

func When added in v0.7.0

func When(predicate func(ctx Context, route RouteInfo) bool, interceptor Interceptor) Interceptor

When conditionally executes an interceptor based on a predicate. If the predicate returns false, the interceptor is skipped (allows).

Example:

// Only require bulk scope for bulk operations
router.POST("/api/resource", handler,
    forge.WithInterceptor(
        When(func(ctx Context, route RouteInfo) bool {
            return ctx.Header("X-Bulk-Operation") == "true"
        }, RequireScopes("bulk:write")),
    ),
)

type InterceptorChain added in v0.7.0

type InterceptorChain struct {
	// contains filtered or unexported fields
}

InterceptorChain represents a chain of interceptors with skip configuration. This is used internally by the router to manage interceptors for a route.

func NewInterceptorChain added in v0.7.0

func NewInterceptorChain(interceptors []Interceptor, skipSet map[string]bool) *InterceptorChain

NewInterceptorChain creates a new interceptor chain.

func (*InterceptorChain) Empty added in v0.7.0

func (c *InterceptorChain) Empty() bool

Empty returns true if the chain has no interceptors.

func (*InterceptorChain) Execute added in v0.7.0

func (c *InterceptorChain) Execute(ctx Context, route RouteInfo) error

Execute runs all interceptors in the chain. Returns an error if any interceptor blocks.

func (*InterceptorChain) Len added in v0.7.0

func (c *InterceptorChain) Len() int

Len returns the number of interceptors in the chain.

type InterceptorFunc added in v0.7.0

type InterceptorFunc func(ctx Context, route RouteInfo) InterceptorResult

InterceptorFunc is a function that inspects a request and decides whether to allow it to proceed.

Interceptors receive:

  • ctx: The forge Context with full request access
  • route: Full RouteInfo for permission/config checking

Return InterceptorResult using convenience functions:

  • Allow() - proceed to handler
  • AllowWithValues(map) - proceed and enrich context
  • Block(err) - reject request with error

type InterceptorResult added in v0.7.0

type InterceptorResult struct {
	// Blocked indicates the request should not proceed
	Blocked bool

	// Error is returned when the interceptor blocks the request
	Error error

	// Values to merge into the context (enrichment)
	// These are merged with existing context values, not replaced
	Values map[string]any
}

InterceptorResult represents the outcome of an interceptor execution. Interceptors can either allow the request to proceed, block it, or enrich the context.

func Allow added in v0.7.0

func Allow() InterceptorResult

Allow returns a result that allows the request to proceed.

func AllowWithValues added in v0.7.0

func AllowWithValues(values map[string]any) InterceptorResult

AllowWithValues allows the request and enriches the context with values. Values are merged with existing context values.

func Block added in v0.7.0

func Block(err error) InterceptorResult

Block returns a result that blocks the request with an error.

func BlockWithValues added in v0.7.0

func BlockWithValues(err error, values map[string]any) InterceptorResult

BlockWithValues blocks the request but still provides values (useful for debugging/logging).

type InternalExtension added in v0.7.0

type InternalExtension interface {
	// ExcludeFromSchemas returns true if all routes from this extension
	// should be excluded from schema generation (OpenAPI, AsyncAPI, oRPC).
	ExcludeFromSchemas() bool
}

InternalExtension is an optional interface that extensions can implement to indicate that all their routes should be excluded from schema generation.

This is useful for:

  • Internal monitoring/metrics extensions
  • Debug/development extensions
  • Admin/management extensions
  • Infrastructure extensions

Example:

type DebugExtension struct {
    forge.ExtensionBase
}

func (e *DebugExtension) ExcludeFromSchemas() bool {
    return true
}

Routes registered by this extension will automatically be excluded from OpenAPI, AsyncAPI, and oRPC schema generation.

type 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 RateLimitResult added in v0.7.0

type RateLimitResult struct {
	Allowed   bool
	Remaining int
	ResetAt   time.Time
}

RateLimitResult contains rate limit check results.

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 ResponseComponents added in v0.7.0

type ResponseComponents struct {
	Headers        map[string]*Header
	BodySchema     *Schema
	HasBody        bool
	BodySchemaName string // Custom schema name from schema:"name" tag
}

ResponseComponents holds all components of a response extracted from a unified schema.

type ResponseDef

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
	Method      string // HTTP method override (for SSE, WebSocket, etc.)
	Summary     string
	Description string
	Tags        []string
	Middleware  []Middleware
	Timeout     time.Duration
	Metadata    map[string]any
	Extensions  map[string]Extension

	// Interceptors run before the handler (after middleware)
	// Unlike middleware, interceptors don't wrap the handler chain -
	// they simply allow/block the request or enrich the context.
	Interceptors     []Interceptor
	SkipInterceptors map[string]bool // Names of interceptors to skip

	// OpenAPI metadata
	OperationID string
	Deprecated  bool

	// SensitiveFieldCleaning enables cleaning of sensitive fields in responses.
	SensitiveFieldCleaning bool
}

RouteConfig holds route configuration.

type RouteExtension

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

	// Interceptors provides access to route interceptors for inspection
	Interceptors     []Interceptor
	SkipInterceptors map[string]bool

	// SensitiveFieldCleaning indicates if sensitive fields should be cleaned in responses.
	SensitiveFieldCleaning bool
}

RouteInfo provides route information for inspection.

type RouteOption

type RouteOption interface {
	Apply(*RouteConfig)
}

RouteOption configures a route.

func WithAcceptedResponse

func WithAcceptedResponse() RouteOption

WithAcceptedResponse creates a 202 Accepted response for async operations.

func WithAsyncAPIBinding

func WithAsyncAPIBinding(bindingType string, binding any) RouteOption

WithAsyncAPIBinding adds protocol-specific bindings bindingType: "ws" or "http" or "server" or "channel" or "operation" or "message" binding: the binding object (e.g., WebSocketChannelBinding, HTTPServerBinding)

func WithAsyncAPIChannelDescription

func WithAsyncAPIChannelDescription(description string) RouteOption

WithAsyncAPIChannelDescription sets the channel description.

func WithAsyncAPIChannelName

func WithAsyncAPIChannelName(name string) RouteOption

WithAsyncAPIChannelName sets a custom channel name (overrides path-based naming).

func WithAsyncAPIChannelSummary

func WithAsyncAPIChannelSummary(summary string) RouteOption

WithAsyncAPIChannelSummary sets the channel summary.

func WithAsyncAPIExternalDocs

func WithAsyncAPIExternalDocs(url, description string) RouteOption

WithAsyncAPIExternalDocs adds external documentation link.

func WithAsyncAPIOperationID

func WithAsyncAPIOperationID(id string) RouteOption

WithAsyncAPIOperationID sets a custom operation ID for AsyncAPI.

func WithAsyncAPISecurity

func WithAsyncAPISecurity(requirements map[string][]string) RouteOption

WithAsyncAPISecurity adds security requirements to the operation.

func WithAsyncAPITags

func WithAsyncAPITags(tags ...string) RouteOption

WithAsyncAPITags adds tags to the AsyncAPI operation.

func WithAuth

func WithAuth(providerNames ...string) RouteOption

WithAuth adds authentication to a route using one or more providers. Multiple providers create an OR condition - any one succeeding allows access.

Example:

router.GET("/protected", handler,
    forge.WithAuth("api-key", "jwt"),
)

func WithAuthAnd

func WithAuthAnd(providerNames ...string) RouteOption

WithAuthAnd requires ALL specified providers to succeed (AND condition). This is useful for multi-factor authentication or combining auth methods.

Example:

router.GET("/high-security", handler,
    forge.WithAuthAnd("api-key", "mfa"),
)

func WithBatchResponse

func WithBatchResponse(itemType any, statusCode int) RouteOption

WithBatchResponse creates a response for batch operations.

func WithCallback

func WithCallback(config CallbackConfig) RouteOption

WithCallback adds a callback definition to a route.

func WithCorrelationID

func WithCorrelationID(location, description string) RouteOption

WithCorrelationID adds correlation ID configuration for request-reply patterns location: runtime expression like "$message.header#/correlationId" description: description of the correlation ID

func WithCreatedResponse

func WithCreatedResponse(resourceType any) RouteOption

WithCreatedResponse creates a 201 Created response with Location header.

func WithDeprecated

func WithDeprecated() RouteOption

func WithDescription

func WithDescription(desc string) RouteOption

func WithDiscriminator

func WithDiscriminator(config DiscriminatorConfig) RouteOption

WithDiscriminator adds discriminator support for polymorphic schemas.

func WithErrorResponses

func WithErrorResponses() RouteOption

WithErrorResponses adds standard HTTP error responses to a route Includes 400, 401, 403, 404, 500.

func WithExtension

func WithExtension(name string, ext Extension) RouteOption

func WithExternalDocs

func WithExternalDocs(description, url string) RouteOption

WithExternalDocs adds external documentation link.

func WithFileUploadResponse

func WithFileUploadResponse(statusCode int) RouteOption

WithFileUploadResponse creates a response for file upload success.

func WithHeaderSchema

func WithHeaderSchema(schemaType any) RouteOption

WithHeaderSchema sets the header parameters schema for OpenAPI generation schemaType should be a struct with header tags.

func WithInterceptor added in v0.7.0

func WithInterceptor(interceptors ...Interceptor) RouteOption

WithInterceptor adds interceptors to a route. Interceptors run in order before the handler. If any interceptor blocks, subsequent interceptors and the handler are not executed.

Interceptors are different from middleware:

  • Middleware wraps the handler chain (before/after)
  • Interceptors run before the handler only, with a simple allow/block decision
  • Interceptors can enrich the context with values
  • Interceptors can be skipped by name

Example:

router.POST("/admin/users", handler,
    forge.WithInterceptor(RequireAdmin, RateLimitCheck),
)

func WithListResponse

func WithListResponse(itemType any, statusCode int) RouteOption

WithListResponse creates a simple list response (array of items).

func WithMessageContentType

func WithMessageContentType(contentType string) RouteOption

WithMessageContentType sets the content type for messages Default is "application/json".

func WithMessageExample

func WithMessageExample(direction, name string, example any) RouteOption

WithMessageExample adds a single message example.

func WithMessageExamples

func WithMessageExamples(direction string, examples map[string]any) RouteOption

WithMessageExamples adds message examples for send/receive direction: "send" or "receive" examples: map of example name to example value

func WithMessageHeaders

func WithMessageHeaders(headersSchema any) RouteOption

WithMessageHeaders defines headers schema for messages headersSchema: Go type with header:"name" tags.

func WithMetadata

func WithMetadata(key string, value any) RouteOption

func WithMethod added in v0.8.0

func WithMethod(method string) RouteOption

WithMethod overrides the HTTP method for a route. Primarily used for SSE/WebSocket endpoints that default to GET.

func WithMiddleware

func WithMiddleware(mw ...Middleware) RouteOption

func 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 WithSensitiveFieldCleaning added in v0.7.0

func WithSensitiveFieldCleaning() RouteOption

WithSensitiveFieldCleaning enables cleaning of sensitive fields in responses. Fields marked with the `sensitive` tag will be processed:

  • sensitive:"true" -> set to zero value
  • sensitive:"redact" -> set to "[REDACTED]"
  • sensitive:"mask:***" -> set to custom mask "***"

func WithServerProtocol

func WithServerProtocol(serverNames ...string) RouteOption

WithServerProtocol specifies which servers this operation should be available on serverNames: list of server names from AsyncAPIConfig.Servers.

func WithSkipInterceptor added in v0.7.0

func WithSkipInterceptor(names ...string) RouteOption

WithSkipInterceptor skips named interceptors for this route. Useful for excluding specific group-level interceptors. Only named interceptors (created with NewInterceptor) can be skipped.

Example:

adminAPI := router.Group("/admin",
    forge.WithGroupInterceptor(RequireAdmin),
)

// Skip admin check for health endpoint
adminAPI.GET("/health", healthHandler,
    forge.WithSkipInterceptor("require-admin"),
)

func WithStandardRESTResponses

func WithStandardRESTResponses(resourceType any) RouteOption

WithStandardRESTResponses adds standard REST CRUD responses for a resource Includes 200 (GET/list), 201 (POST), 204 (DELETE), 400, 404, 500.

func WithStrictValidation

func WithStrictValidation() RouteOption

WithStrictValidation enables strict validation (validates both request and response).

func WithSummary

func WithSummary(summary string) RouteOption

func WithTags

func WithTags(tags ...string) RouteOption

func WithTimeout

func WithTimeout(d time.Duration) RouteOption

func WithValidation

func WithValidation(enabled bool) RouteOption

WithValidation adds validation middleware to a route.

func WithValidationErrorResponse

func WithValidationErrorResponse() RouteOption

WithValidationErrorResponse adds a 422 Unprocessable Entity response for validation errors.

func WithWebSocketMessages

func WithWebSocketMessages(sendSchema, receiveSchema any) RouteOption

WithWebSocketMessages defines send/receive message schemas for WebSocket endpoints sendSchema: messages that the client sends to the server (action: send) receiveSchema: messages that the server sends to the client (action: receive).

func WithWebTransport

func WithWebTransport(config WebTransportConfig) RouteOption

WithWebTransport enables WebTransport support with the given configuration.

func WithWebTransportDatagrams

func WithWebTransportDatagrams(enabled bool) RouteOption

WithWebTransportDatagrams enables datagram support for WebTransport.

func WithWebTransportStreams

func WithWebTransportStreams(maxBidi, maxUni int64) RouteOption

WithWebTransportStreams sets the maximum number of streams.

func WithWebhook

func WithWebhook(name string, operation *CallbackOperation) RouteOption

WithWebhook adds a webhook definition to the OpenAPI spec Webhooks are documented at the API level, not per-route.

type Router

type Router interface {
	// HTTP Methods - register routes
	GET(path string, handler any, opts ...RouteOption) error
	POST(path string, handler any, opts ...RouteOption) error
	PUT(path string, handler any, opts ...RouteOption) error
	DELETE(path string, handler any, opts ...RouteOption) error
	PATCH(path string, handler any, opts ...RouteOption) error
	OPTIONS(path string, handler any, opts ...RouteOption) error
	HEAD(path string, handler any, opts ...RouteOption) error

	// Grouping - organize routes
	Group(prefix string, opts ...GroupOption) Router

	// Middleware - wrap handlers
	Use(middleware ...Middleware)
	UseGlobal(middleware ...Middleware)

	// Controller registration
	RegisterController(controller Controller) error

	// Lifecycle
	Start(ctx context.Context) error
	Stop(ctx context.Context) error

	// HTTP serving
	ServeHTTP(w http.ResponseWriter, r *http.Request)
	Handler() http.Handler

	// Inspection
	Routes() []RouteInfo
	RouteByName(name string) (RouteInfo, bool)
	RoutesByTag(tag string) []RouteInfo
	RoutesByMetadata(key string, value any) []RouteInfo

	// OpenAPI
	OpenAPISpec() *OpenAPISpec

	// AsyncAPI
	AsyncAPISpec() *AsyncAPISpec

	// Streaming
	WebSocket(path string, handler WebSocketHandler, opts ...RouteOption) error
	EventStream(path string, handler SSEHandler, opts ...RouteOption) error
	SSE(path string, handler Handler, opts ...RouteOption) error

	// WebTransport
	WebTransport(path string, handler WebTransportHandler, opts ...RouteOption) error
	EnableWebTransport(config WebTransportConfig) error
	StartHTTP3(addr string, tlsConfig *tls.Config) error
	StopHTTP3() error
}

Router provides HTTP routing with multiple backend support.

func GetRouter added in v0.5.0

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