Documentation
ΒΆ
Index ΒΆ
- Constants
- Variables
- func Must[T any](c Container, name string) T
- func MustGet[T any](cm ConfigManager, key string) T
- func MustScope[T any](s Scope, name string) T
- func RegisterInterface[I, T any](c Container, name string, factory func(Container) (T, error), ...) error
- func RegisterScoped[T any](c Container, name string, factory func(Container) (T, error)) error
- func RegisterScopedInterface[I, T any](c Container, name string, factory func(Container) (T, error)) error
- func RegisterSingleton[T any](c Container, name string, factory func(Container) (T, error)) error
- func RegisterSingletonInterface[I, T any](c Container, name string, factory func(Container) (T, error)) error
- func RegisterTransient[T any](c Container, name string, factory func(Container) (T, error)) error
- func RegisterTransientInterface[I, T any](c Container, name string, factory func(Container) (T, error)) error
- func RegisterValue[T any](c Container, name string, instance T) error
- func Resolve[T any](c Container, name string) (T, error)
- func ResolveScope[T any](s Scope, name string) (T, error)
- func SafeGet[T any](cm ConfigManager, key string) (T, error)
- type App
- type AppConfig
- type AppInfo
- type AsyncAPIChannel
- type AsyncAPIChannelBindings
- type AsyncAPIChannelReference
- type AsyncAPIComponents
- type AsyncAPIConfig
- type AsyncAPICorrelationID
- type AsyncAPIInfo
- type AsyncAPIMessage
- type AsyncAPIMessageBindings
- type AsyncAPIMessageExample
- type AsyncAPIMessageReference
- type AsyncAPIMessageTrait
- type AsyncAPIOAuthFlows
- type AsyncAPIOperation
- type AsyncAPIOperationBindings
- type AsyncAPIOperationReply
- type AsyncAPIOperationReplyAddress
- type AsyncAPIOperationTrait
- type AsyncAPIParameter
- type AsyncAPISecurityRequirement
- type AsyncAPISecurityScheme
- type AsyncAPIServer
- type AsyncAPIServerBindings
- type AsyncAPIServerReference
- type AsyncAPISpec
- type AsyncAPITag
- type BaseExtension
- func (e *BaseExtension) App() App
- func (e *BaseExtension) Dependencies() []string
- func (e *BaseExtension) Description() string
- func (e *BaseExtension) Health(ctx context.Context) error
- func (e *BaseExtension) IsStarted() bool
- func (e *BaseExtension) LoadConfig(key string, target interface{}, programmaticConfig interface{}, ...) error
- func (e *BaseExtension) Logger() Logger
- func (e *BaseExtension) MarkStarted()
- func (e *BaseExtension) MarkStopped()
- func (e *BaseExtension) Metrics() Metrics
- func (e *BaseExtension) Name() string
- func (e *BaseExtension) Register(app App) error
- func (e *BaseExtension) SetDependencies(deps []string)
- func (e *BaseExtension) SetLogger(logger Logger)
- func (e *BaseExtension) SetMetrics(metrics Metrics)
- func (e *BaseExtension) Start(ctx context.Context) error
- func (e *BaseExtension) Stop(ctx context.Context) error
- func (e *BaseExtension) Version() string
- type BindOptions
- type BunRouterAdapter
- type CallbackConfig
- func NewCompletionCallbackConfig(callbackURLExpression string, resultSchema interface{}) CallbackConfig
- func NewEventCallbackConfig(callbackURLExpression string, eventSchema interface{}) CallbackConfig
- func NewStatusCallbackConfig(callbackURLExpression string, statusSchema interface{}) CallbackConfig
- type CallbackOperation
- type ChangeType
- type Components
- type ConfigChange
- type ConfigErrorHandler
- type ConfigManager
- type ConfigSource
- type ConfigSourceFactory
- type ConfigSourceOptions
- type Configurable
- type ConfigurableExtension
- type Connection
- type Contact
- type Container
- type Context
- type Controller
- type ControllerWithDependencies
- type ControllerWithMiddleware
- type ControllerWithPrefix
- type ControllerWithTags
- type Counter
- type DefaultConfigErrorHandler
- type Discriminator
- type DiscriminatorConfig
- type Disposable
- type Encoding
- type ErrorHandler
- type Example
- type Extension
- type ExtensionConfigLoader
- type ExtensionInfo
- type ExternalDocs
- type ExternalDocsDef
- type Factory
- type Field
- type Gauge
- type GetOption
- type GetOptions
- type GroupConfig
- type GroupOption
- func WithGroupAuth(providerNames ...string) GroupOption
- func WithGroupAuthAnd(providerNames ...string) GroupOption
- func WithGroupMetadata(key string, value any) GroupOption
- func WithGroupMiddleware(mw ...Middleware) GroupOption
- func WithGroupRequiredScopes(scopes ...string) GroupOption
- func WithGroupTags(tags ...string) GroupOption
- type HTTPChannelBinding
- type HTTPError
- type HTTPMessageBinding
- type HTTPOperationBinding
- type HTTPServerBinding
- type HandlerPattern
- type Header
- type HealthCheck
- type HealthChecker
- type HealthConfig
- type HealthManager
- type HealthReport
- type HealthResult
- type HealthStatus
- type Histogram
- type HotReloadableExtension
- type Info
- type License
- type Link
- type LogLevel
- type Logger
- type LoggerConfig
- type LoggingConfig
- type ManagerConfig
- type MediaType
- type MetricType
- type Metrics
- type MetricsConfig
- type Middleware
- type MiddlewareFunc
- type OAuthFlow
- type OAuthFlows
- type ObservableExtension
- type OpenAPIConfig
- type OpenAPIServer
- type OpenAPISpec
- type OpenAPITag
- type Operation
- type Parameter
- type ParameterDef
- type PathItem
- type RegisterOption
- type RequestBody
- type RequestBodyDef
- type Response
- type ResponseDef
- type ResponseSchemaDef
- type RouteConfig
- type RouteExtension
- type RouteInfo
- type RouteOption
- func WithAcceptedResponse() RouteOption
- func WithAsyncAPIBinding(bindingType string, binding interface{}) RouteOption
- func WithAsyncAPIChannelDescription(description string) RouteOption
- func WithAsyncAPIChannelName(name string) RouteOption
- func WithAsyncAPIChannelSummary(summary string) RouteOption
- func WithAsyncAPIExternalDocs(url, description string) RouteOption
- func WithAsyncAPIOperationID(id string) RouteOption
- func WithAsyncAPISecurity(requirements map[string][]string) RouteOption
- func WithAsyncAPITags(tags ...string) RouteOption
- func WithAuth(providerNames ...string) RouteOption
- func WithAuthAnd(providerNames ...string) RouteOption
- func WithBatchResponse(itemType interface{}, statusCode int) RouteOption
- func WithCallback(config CallbackConfig) RouteOption
- func WithCorrelationID(location, description string) RouteOption
- func WithCreatedResponse(resourceType interface{}) RouteOption
- func WithDeprecated() RouteOption
- func WithDescription(desc string) RouteOption
- func WithDiscriminator(config DiscriminatorConfig) RouteOption
- func WithErrorResponses() RouteOption
- func WithExtension(name string, ext Extension) RouteOption
- func WithExternalDocs(description, url string) RouteOption
- func WithFileUploadResponse(statusCode int) RouteOption
- func WithHeaderSchema(schemaType interface{}) RouteOption
- func WithListResponse(itemType interface{}, statusCode int) RouteOption
- func WithMessageContentType(contentType string) RouteOption
- func WithMessageExample(direction, name string, example interface{}) RouteOption
- func WithMessageExamples(direction string, examples map[string]interface{}) RouteOption
- func WithMessageHeaders(headersSchema interface{}) RouteOption
- func WithMetadata(key string, value any) RouteOption
- func WithMiddleware(mw ...Middleware) RouteOption
- func WithName(name string) RouteOption
- func WithNoContentResponse() RouteOption
- func WithORPCExclude() RouteOption
- func WithORPCMethod(methodName string) RouteOption
- func WithORPCParams(schema any) RouteOption
- func WithORPCPrimaryResponse(statusCode int) RouteOption
- func WithORPCResult(schema any) RouteOption
- func WithORPCTags(tags ...string) RouteOption
- func WithOperationID(id string) RouteOption
- func WithPaginatedResponse(itemType interface{}, statusCode int) RouteOption
- func WithParameter(name, in, description string, required bool, example interface{}) RouteOption
- func WithQuerySchema(schemaType interface{}) RouteOption
- func WithRequestBody(description string, required bool, example interface{}) RouteOption
- func WithRequestBodySchema(schemaOrType interface{}) RouteOption
- func WithRequestContentTypes(types ...string) RouteOption
- func WithRequestExample(name string, example interface{}) RouteOption
- func WithRequestSchema(schemaOrType interface{}) RouteOption
- func WithRequiredAuth(providerName string, scopes ...string) RouteOption
- func WithResponse(code int, description string, example interface{}) RouteOption
- func WithResponseContentTypes(types ...string) RouteOption
- func WithResponseExample(statusCode int, name string, example interface{}) RouteOption
- func WithResponseSchema(statusCode int, description string, schemaOrType interface{}) RouteOption
- func WithSSEMessage(eventName string, schema interface{}) RouteOption
- func WithSSEMessages(messageSchemas map[string]interface{}) RouteOption
- func WithSchemaRef(name string, schema interface{}) RouteOption
- func WithSecurity(schemes ...string) RouteOption
- func WithServerProtocol(serverNames ...string) RouteOption
- func WithStandardRESTResponses(resourceType interface{}) RouteOption
- func WithStrictValidation() RouteOption
- func WithSummary(summary string) RouteOption
- func WithTags(tags ...string) RouteOption
- func WithTimeout(d time.Duration) RouteOption
- func WithValidation(enabled bool) RouteOption
- func WithValidationErrorResponse() RouteOption
- func WithWebSocketMessages(sendSchema, receiveSchema interface{}) RouteOption
- func WithWebhook(name string, operation *CallbackOperation) RouteOption
- type Router
- type RouterAdapter
- type RouterOption
- func WithAdapter(adapter RouterAdapter) RouterOption
- func WithAsyncAPI(config AsyncAPIConfig) RouterOption
- func WithContainer(container Container) RouterOption
- func WithErrorHandler(handler ErrorHandler) RouterOption
- func WithHealth(config HealthConfig) RouterOption
- func WithLogger(logger Logger) RouterOption
- func WithMetrics(config MetricsConfig) RouterOption
- func WithOpenAPI(config OpenAPIConfig) RouterOption
- func WithRecovery() RouterOption
- type SSEHandler
- type Schema
- type Scope
- type SecretProvider
- type SecretsConfig
- type SecretsManager
- type SecurityRequirement
- type SecurityScheme
- type Service
- type ServiceError
- type ServiceInfo
- type SourceConfig
- type SourceEvent
- type SourceEventHandler
- type SourceMetadata
- type SourceRegistry
- type Stream
- type StreamConfig
- type SugarLogger
- type ValidationConfig
- type ValidationError
- type ValidationErrors
- type ValidationMode
- type ValidationOptions
- type ValidationRule
- type Validator
- type WatchContext
- type Watcher
- type WatcherConfig
- type WebSocketChannelBinding
- type WebSocketHandler
- type WebSocketMessageBinding
- type WebSocketOperationBinding
- type WebSocketServerBinding
- type WebTransportConfig
- type WebTransportHandler
- type WebTransportSession
- type WebTransportStream
Constants ΒΆ
const ( ChangeTypeSet = config.ChangeTypeSet ChangeTypeUpdate = config.ChangeTypeUpdate ChangeTypeDelete = config.ChangeTypeDelete ChangeTypeReload = config.ChangeTypeReload )
Constants
const ( ValidationModePermissive = config.ValidationModePermissive ValidationModeStrict = config.ValidationModeStrict ValidationModeLoose = config.ValidationModeLoose )
const ( HealthStatusHealthy = shared.HealthStatusHealthy HealthStatusDegraded = shared.HealthStatusDegraded HealthStatusUnhealthy = shared.HealthStatusUnhealthy HealthStatusUnknown = shared.HealthStatusUnknown )
const ( LevelInfo = logger.LevelInfo LevelWarn = logger.LevelWarn LevelError = logger.LevelError LevelFatal = logger.LevelFatal LevelDebug = logger.LevelDebug )
Re-export logger constants
const ( MetricTypeCounter = shared.MetricTypeCounter MetricTypeGauge = shared.MetricTypeGauge MetricTypeHistogram = shared.MetricTypeHistogram MetricTypeTimer = shared.MetricTypeTimer )
Metric type constants
const ConfigKey = "config"
ConfigKey is the service key for configuration manager
Variables ΒΆ
var ( NewManager = config.NewManager NewSourceRegistry = config.NewSourceRegistry NewValidator = config.NewValidator NewWatcher = config.NewWatcher NewSecretsManager = config.NewSecretsManager )
var ( WithDefault = config.WithDefault WithRequired = config.WithRequired WithValidator = config.WithValidator WithTransform = config.WithTransform WithOnMissing = config.WithOnMissing AllowEmpty = config.AllowEmpty WithCacheKey = config.WithCacheKey )
var ( ErrServiceNotFound = errors.ErrServiceNotFound ErrServiceAlreadyExists = errors.ErrServiceAlreadyExists ErrCircularDependency = errors.ErrCircularDependency ErrInvalidFactory = errors.ErrInvalidFactory ErrTypeMismatch = errors.ErrTypeMismatch ErrLifecycleTimeout = errors.ErrLifecycleTimeout ErrContainerStarted = errors.ErrContainerStarted ErrContainerStopped = errors.ErrContainerStopped ErrScopeEnded = errors.ErrScopeEnded )
Re-export error constructors for backward compatibility
var ( ErrServiceNotFoundSentinel = errors.ErrServiceNotFoundSentinel ErrServiceAlreadyExistsSentinel = errors.ErrServiceAlreadyExistsSentinel ErrCircularDependencySentinel = errors.ErrCircularDependencySentinel ErrInvalidConfigSentinel = errors.ErrInvalidConfigSentinel ErrValidationErrorSentinel = errors.ErrValidationErrorSentinel ErrLifecycleErrorSentinel = errors.ErrLifecycleErrorSentinel ErrContextCancelledSentinel = errors.ErrContextCancelledSentinel ErrTimeoutErrorSentinel = errors.ErrTimeoutErrorSentinel ErrConfigErrorSentinel = errors.ErrConfigErrorSentinel )
Re-export sentinel errors for error comparison using errors.Is()
var ( NewLogger = logger.NewLogger NewDevelopmentLogger = logger.NewDevelopmentLogger NewProductionLogger = logger.NewProductionLogger NewNoopLogger = logger.NewNoopLogger GetGlobalLogger = logger.GetGlobalLogger SetGlobalLogger = logger.SetGlobalLogger )
Re-export logger constructors
var ( // Basic types String = logger.String Int = logger.Int Int8 = logger.Int8 Int16 = logger.Int16 Int32 = logger.Int32 Int64 = logger.Int64 Uint = logger.Uint Uint8 = logger.Uint8 Uint16 = logger.Uint16 Uint32 = logger.Uint32 Uint64 = logger.Uint64 Float32 = logger.Float32 Float64 = logger.Float64 Bool = logger.Bool // Time and duration Time = logger.Time Duration = logger.Duration // Error Error = logger.Error // Advanced Stringer = logger.Stringer Any = logger.Any Stack = logger.Stack Strings = logger.Strings // HTTP fields HTTPMethod = logger.HTTPMethod HTTPStatus = logger.HTTPStatus HTTPPath = logger.HTTPPath HTTPURL = logger.HTTPURL HTTPUserAgent = logger.HTTPUserAgent // Database fields DatabaseQuery = logger.DatabaseQuery DatabaseTable = logger.DatabaseTable DatabaseRows = logger.DatabaseRows // Service fields ServiceName = logger.ServiceName ServiceVersion = logger.ServiceVersion ServiceEnvironment = logger.ServiceEnvironment // Context fields RequestID = logger.RequestID TraceID = logger.TraceID UserID = logger.UserID ContextFields = logger.ContextFields // Custom Custom = logger.Custom Lazy = logger.Lazy )
Re-export field constructors
var ( LoggerFromContext = logger.LoggerFromContext WithRequestID = logger.WithRequestID RequestIDFromContext = logger.RequestIDFromContext WithTraceID = logger.WithTraceID TraceIDFromContext = logger.TraceIDFromContext WithUserID = logger.WithUserID UserIDFromContext = logger.UserIDFromContext )
Re-export context helpers (note: WithLogger conflicts with context.go, use logger.WithLogger directly)
var ( Track = logger.Track TrackWithLogger = logger.TrackWithLogger TrackWithFields = logger.TrackWithFields LogPanic = logger.LogPanic LogPanicWithFields = logger.LogPanicWithFields )
Re-export utility functions
var ( HTTPRequestGroup = logger.HTTPRequestGroup DatabaseQueryGroup = logger.DatabaseQueryGroup ServiceInfoGroup = logger.ServiceInfoGroup )
Re-export field groups
var ( NewHTTPError = errors.NewHTTPError BadRequest = errors.BadRequest Forbidden = errors.Forbidden NotFound = errors.NotFound InternalError = errors.InternalError )
var (
ErrExtensionNotRegistered = fmt.Errorf("extension not registered with app")
)
Extension-specific errors
var NewServiceError = errors.NewServiceError
Re-export error constructors for backward compatibility
Functions ΒΆ
func MustGet ΒΆ
func MustGet[T any](cm ConfigManager, key string) T
MustGet returns a value or panics if not found
func RegisterInterface ΒΆ
func RegisterInterface[I, T any](c Container, name string, factory func(Container) (T, error), opts ...RegisterOption) error
RegisterInterface registers an implementation as an interface Supports all lifecycle options (Singleton, Scoped, Transient)
func RegisterScoped ΒΆ
RegisterScoped is a convenience wrapper for request-scoped services
func RegisterScopedInterface ΒΆ
func RegisterScopedInterface[I, T any](c Container, name string, factory func(Container) (T, error)) error
RegisterScopedInterface is a convenience wrapper
func RegisterSingleton ΒΆ
RegisterSingleton is a convenience wrapper
func RegisterSingletonInterface ΒΆ
func RegisterSingletonInterface[I, T any](c Container, name string, factory func(Container) (T, error)) error
RegisterSingletonInterface is a convenience wrapper
func RegisterTransient ΒΆ
RegisterTransient is a convenience wrapper
func RegisterTransientInterface ΒΆ
func RegisterTransientInterface[I, T any](c Container, name string, factory func(Container) (T, error)) error
RegisterTransientInterface is a convenience wrapper
func RegisterValue ΒΆ
RegisterValue registers a pre-built instance (always singleton)
func ResolveScope ΒΆ
ResolveScope is a helper for resolving from a scope
Types ΒΆ
type App ΒΆ
type App interface {
// Core components
Container() Container
Router() Router
Config() ConfigManager
Logger() Logger
Metrics() Metrics
HealthManager() HealthManager
// Lifecycle
Start(ctx context.Context) error
Stop(ctx context.Context) error
Run() error // Blocks until shutdown signal
// Registration
RegisterService(name string, factory Factory, opts ...RegisterOption) error
RegisterController(controller Controller) error
RegisterExtension(ext Extension) error
// Information
Name() string
Version() string
Environment() string
StartTime() time.Time
Uptime() time.Duration
// Extensions
Extensions() []Extension
GetExtension(name string) (Extension, error)
}
App represents a Forge application with lifecycle management
type AppConfig ΒΆ
type AppConfig struct {
// Basic info
Name string
Version string
Description string
Environment string // "development", "staging", "production"
// Components
ConfigManager ConfigManager
Logger Logger
// Router options
RouterOptions []RouterOption
// Observability
MetricsConfig MetricsConfig
HealthConfig HealthConfig
ErrorHandler ErrorHandler
// Server
HTTPAddress string // Default: ":8080"
HTTPTimeout time.Duration // Default: 30s
// Shutdown
ShutdownTimeout time.Duration // Default: 30s
ShutdownSignals []os.Signal // Default: SIGINT, SIGTERM
// Extensions
Extensions []Extension // Extensions to register with the app
}
AppConfig configures the application
func DefaultAppConfig ΒΆ
func DefaultAppConfig() AppConfig
DefaultAppConfig returns a default application configuration
type AppInfo ΒΆ
type AppInfo struct {
Name string `json:"name"`
Version string `json:"version"`
Description string `json:"description"`
Environment string `json:"environment"`
StartTime time.Time `json:"start_time"`
Uptime time.Duration `json:"uptime"`
GoVersion string `json:"go_version"`
Services []string `json:"services"`
Routes int `json:"routes"`
Extensions []ExtensionInfo `json:"extensions,omitempty"`
}
AppInfo represents application information returned by /_/info endpoint
type AsyncAPIChannel ΒΆ
type AsyncAPIChannel = shared.AsyncAPIChannel
AsyncAPIChannel represents a channel in the AsyncAPI spec
type AsyncAPIChannelBindings ΒΆ
type AsyncAPIChannelBindings = shared.AsyncAPIChannelBindings
AsyncAPIChannelBindings contains protocol-specific channel bindings
type AsyncAPIChannelReference ΒΆ
type AsyncAPIChannelReference = shared.AsyncAPIChannelReference
AsyncAPIChannelReference references a channel
type AsyncAPIComponents ΒΆ
type AsyncAPIComponents = shared.AsyncAPIComponents
AsyncAPIComponents holds reusable objects for the API spec
type AsyncAPIConfig ΒΆ
type AsyncAPIConfig = shared.AsyncAPIConfig
AsyncAPIConfig configures AsyncAPI 3.0.0 generation
type AsyncAPICorrelationID ΒΆ
type AsyncAPICorrelationID = shared.AsyncAPICorrelationID
AsyncAPICorrelationID specifies a correlation ID for request-reply patterns
type AsyncAPIInfo ΒΆ
type AsyncAPIInfo = shared.AsyncAPIInfo
AsyncAPIInfo provides metadata about the API
type AsyncAPIMessage ΒΆ
type AsyncAPIMessage = shared.AsyncAPIMessage
AsyncAPIMessage represents a message in the AsyncAPI spec
type AsyncAPIMessageBindings ΒΆ
type AsyncAPIMessageBindings = shared.AsyncAPIMessageBindings
AsyncAPIMessageBindings contains protocol-specific message bindings
type AsyncAPIMessageExample ΒΆ
type AsyncAPIMessageExample = shared.AsyncAPIMessageExample
AsyncAPIMessageExample represents an example of a message
type AsyncAPIMessageReference ΒΆ
type AsyncAPIMessageReference = shared.AsyncAPIMessageReference
AsyncAPIMessageReference references a message
type AsyncAPIMessageTrait ΒΆ
type AsyncAPIMessageTrait = shared.AsyncAPIMessageTrait
AsyncAPIMessageTrait represents reusable message characteristics
type AsyncAPIOAuthFlows ΒΆ
type AsyncAPIOAuthFlows = shared.AsyncAPIOAuthFlows
AsyncAPIOAuthFlows defines OAuth 2.0 flows
type AsyncAPIOperation ΒΆ
type AsyncAPIOperation = shared.AsyncAPIOperation
AsyncAPIOperation represents an operation in the AsyncAPI spec
type AsyncAPIOperationBindings ΒΆ
type AsyncAPIOperationBindings = shared.AsyncAPIOperationBindings
AsyncAPIOperationBindings contains protocol-specific operation bindings
type AsyncAPIOperationReply ΒΆ
type AsyncAPIOperationReply = shared.AsyncAPIOperationReply
AsyncAPIOperationReply represents the reply configuration for an operation
type AsyncAPIOperationReplyAddress ΒΆ
type AsyncAPIOperationReplyAddress = shared.AsyncAPIOperationReplyAddress
AsyncAPIOperationReplyAddress represents the reply address
type AsyncAPIOperationTrait ΒΆ
type AsyncAPIOperationTrait = shared.AsyncAPIOperationTrait
AsyncAPIOperationTrait represents reusable operation characteristics
type AsyncAPIParameter ΒΆ
type AsyncAPIParameter = shared.AsyncAPIParameter
AsyncAPIParameter represents a parameter in channel address
type AsyncAPISecurityRequirement ΒΆ
type AsyncAPISecurityRequirement = shared.AsyncAPISecurityRequirement
AsyncAPISecurityRequirement lists required security schemes
type AsyncAPISecurityScheme ΒΆ
type AsyncAPISecurityScheme = shared.AsyncAPISecurityScheme
AsyncAPISecurityScheme defines a security scheme
type AsyncAPIServer ΒΆ
type AsyncAPIServer = shared.AsyncAPIServer
AsyncAPIServer represents a server in the AsyncAPI spec
type AsyncAPIServerBindings ΒΆ
type AsyncAPIServerBindings = shared.AsyncAPIServerBindings
AsyncAPIServerBindings contains protocol-specific server bindings
type AsyncAPIServerReference ΒΆ
type AsyncAPIServerReference = shared.AsyncAPIServerReference
AsyncAPIServerReference references a server
type AsyncAPISpec ΒΆ
type AsyncAPISpec = shared.AsyncAPISpec
AsyncAPISpec represents the complete AsyncAPI 3.0.0 specification
type AsyncAPITag ΒΆ
type AsyncAPITag = shared.AsyncAPITag
AsyncAPITag represents a tag in the AsyncAPI spec
type BaseExtension ΒΆ
type BaseExtension struct {
// contains filtered or unexported fields
}
BaseExtension provides common functionality for implementing extensions. Extensions can embed BaseExtension to get standard implementations of common methods.
Example usage:
type MyExtension struct {
*forge.BaseExtension
config MyConfig
client *MyClient
}
func NewMyExtension(config MyConfig) forge.Extension {
return &MyExtension{
BaseExtension: forge.NewBaseExtension("my-ext", "1.0.0", "My extension"),
config: config,
}
}
func NewBaseExtension ΒΆ
func NewBaseExtension(name, version, description string) *BaseExtension
NewBaseExtension creates a new base extension with the given identity
func (*BaseExtension) App ΒΆ
func (e *BaseExtension) App() App
App returns the app instance this extension is registered with
func (*BaseExtension) Dependencies ΒΆ
func (e *BaseExtension) Dependencies() []string
Dependencies returns the extension dependencies
func (*BaseExtension) Description ΒΆ
func (e *BaseExtension) Description() string
Description returns the extension description
func (*BaseExtension) Health ΒΆ
func (e *BaseExtension) Health(ctx context.Context) error
Health is a default implementation that always returns healthy. Extensions should override this to implement actual health checks.
func (*BaseExtension) IsStarted ΒΆ
func (e *BaseExtension) IsStarted() bool
IsStarted returns true if the extension has been started
func (*BaseExtension) LoadConfig ΒΆ
func (e *BaseExtension) LoadConfig( key string, target interface{}, programmaticConfig interface{}, defaults interface{}, requireConfig bool, ) error
LoadConfig loads configuration for this extension from ConfigManager.
It tries the following keys in order:
- "extensions.{key}" - Namespaced pattern (preferred)
- "{key}" - Top-level pattern (legacy/v1 compatibility)
Parameters:
- key: The config key (e.g., "cache", "mcp")
- target: Pointer to config struct to populate
- programmaticConfig: Config provided programmatically (may be partially filled)
- defaults: Default config to use if nothing found
- requireConfig: If true, returns error when config not found; if false, uses defaults
Example:
func (e *Extension) Register(app forge.App) error {
if err := e.BaseExtension.Register(app); err != nil {
return err
}
// Load config from ConfigManager
finalConfig := DefaultConfig()
if err := e.LoadConfig("cache", &finalConfig, e.config, DefaultConfig(), false); err != nil {
return err
}
e.config = finalConfig
// ... rest of registration
}
func (*BaseExtension) Logger ΒΆ
func (e *BaseExtension) Logger() Logger
Logger returns the extension's logger
func (*BaseExtension) MarkStarted ΒΆ
func (e *BaseExtension) MarkStarted()
MarkStarted marks the extension as started
func (*BaseExtension) MarkStopped ΒΆ
func (e *BaseExtension) MarkStopped()
MarkStopped marks the extension as stopped
func (*BaseExtension) Metrics ΒΆ
func (e *BaseExtension) Metrics() Metrics
Metrics returns the extension's metrics
func (*BaseExtension) Register ΒΆ
func (e *BaseExtension) Register(app App) error
Register is a default implementation that does nothing. Extensions should override this to register their services.
func (*BaseExtension) SetDependencies ΒΆ
func (e *BaseExtension) SetDependencies(deps []string)
SetDependencies sets the extension dependencies
func (*BaseExtension) SetLogger ΒΆ
func (e *BaseExtension) SetLogger(logger Logger)
SetLogger sets the logger for this extension
func (*BaseExtension) SetMetrics ΒΆ
func (e *BaseExtension) SetMetrics(metrics Metrics)
SetMetrics sets the metrics for this extension
func (*BaseExtension) Start ΒΆ
func (e *BaseExtension) Start(ctx context.Context) error
Start is a default implementation that does nothing. Extensions should override this to start their services.
func (*BaseExtension) Stop ΒΆ
func (e *BaseExtension) Stop(ctx context.Context) error
Stop is a default implementation that does nothing. Extensions should override this to stop their services.
func (*BaseExtension) Version ΒΆ
func (e *BaseExtension) Version() string
Version returns the extension version
type BindOptions ΒΆ
type BindOptions = configcore.BindOptions
Configuration Options
func DefaultBindOptions ΒΆ
func DefaultBindOptions() BindOptions
DefaultBindOptions returns default bind options
type BunRouterAdapter ΒΆ
type BunRouterAdapter = router.BunRouterAdapter
BunRouterAdapter wraps uptrace/bunrouter
type CallbackConfig ΒΆ
type CallbackConfig = router.CallbackConfig
CallbackConfig defines a callback (webhook) for an operation
func NewCompletionCallbackConfig ΒΆ
func NewCompletionCallbackConfig(callbackURLExpression string, resultSchema interface{}) CallbackConfig
NewCompletionCallbackConfig creates a callback config for async operation completion
func NewEventCallbackConfig ΒΆ
func NewEventCallbackConfig(callbackURLExpression string, eventSchema interface{}) CallbackConfig
NewEventCallbackConfig creates a callback config for event notifications
func NewStatusCallbackConfig ΒΆ
func NewStatusCallbackConfig(callbackURLExpression string, statusSchema interface{}) CallbackConfig
NewStatusCallbackConfig creates a callback config for status updates
type CallbackOperation ΒΆ
type CallbackOperation = router.CallbackOperation
CallbackOperation defines an operation that will be called back
func NewCallbackOperation ΒΆ
func NewCallbackOperation(summary, description string) *CallbackOperation
NewCallbackOperation creates a new callback operation
type Components ΒΆ
type Components = shared.Components
Components holds reusable objects for the API spec
type ConfigErrorHandler ΒΆ
type ConfigErrorHandler interface {
// HandleError handles an error
HandleError(ctx Context, err error) error
// ShouldRetry determines if an operation should be retried
ShouldRetry(err error) bool
// GetRetryDelay returns the delay before retrying
GetRetryDelay(attempt int, err error) time.Duration
}
ConfigErrorHandler defines how errors should be handled in the config system
type ConfigManager ΒΆ
type ConfigManager = configcore.ConfigManager
Configuration Manager
func NewDefaultConfigManager ΒΆ
func NewDefaultConfigManager( l logger.Logger, m Metrics, e ErrorHandler, ) ConfigManager
Helper to create a default config manager (stub for now)
type ConfigSourceFactory ΒΆ
type ConfigSourceFactory = config.ConfigSourceFactory
Configuration Sources
type ConfigSourceOptions ΒΆ
type ConfigSourceOptions = config.ConfigSourceOptions
Configuration Sources
type Configurable ΒΆ
type Configurable = shared.Configurable
Configurable is optional for services that need configuration
type ConfigurableExtension ΒΆ
type ConfigurableExtension interface {
Extension
// Configure configures the extension with the provided config object
Configure(config any) error
}
ConfigurableExtension is an optional interface for extensions that support configuration.
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 DefaultConfigErrorHandler ΒΆ
type DefaultConfigErrorHandler struct {
// contains filtered or unexported fields
}
DefaultConfigErrorHandler is the default error handler for config
func NewDefaultConfigErrorHandler ΒΆ
func NewDefaultConfigErrorHandler(logger Logger) *DefaultConfigErrorHandler
NewDefaultConfigErrorHandler creates a new default config error handler
func (*DefaultConfigErrorHandler) GetRetryDelay ΒΆ
func (h *DefaultConfigErrorHandler) GetRetryDelay(attempt int, err error) time.Duration
GetRetryDelay returns the delay before retrying
func (*DefaultConfigErrorHandler) HandleError ΒΆ
func (h *DefaultConfigErrorHandler) HandleError(ctx Context, err error) error
HandleError handles an error
func (*DefaultConfigErrorHandler) ShouldRetry ΒΆ
func (h *DefaultConfigErrorHandler) ShouldRetry(err error) bool
ShouldRetry determines if an operation should be retried
type DiscriminatorConfig ΒΆ
type DiscriminatorConfig = router.DiscriminatorConfig
DiscriminatorConfig defines discriminator for polymorphic types
type Disposable ΒΆ
type Disposable = shared.Disposable
Disposable is optional for scoped services that need cleanup
type ErrorHandler ΒΆ
type ErrorHandler = shared.ErrorHandler
ErrorHandler handles errors from handlers
func NewDefaultErrorHandler ΒΆ
func NewDefaultErrorHandler(l Logger) ErrorHandler
NewDefaultErrorHandler creates a default error handler
type Extension ΒΆ
type Extension interface {
// Name returns the unique name of the extension
Name() string
// Version returns the semantic version of the extension
Version() string
// Description returns a human-readable description
Description() string
// Register registers the extension's services with the DI container.
// This is called before Start(), allowing the extension to:
// - Register services with the DI container
// - Access core services (logger, metrics, config)
// - Set up internal state
Register(app App) error
// Start starts the extension.
// This is called after all extensions have been registered and the DI container has started.
Start(ctx context.Context) error
// Stop stops the extension gracefully.
// Extensions are stopped in reverse dependency order.
Stop(ctx context.Context) error
// Health checks if the extension is healthy.
// This is called periodically by the health check system.
// Return nil if healthy, error otherwise.
Health(ctx context.Context) error
// Dependencies returns the names of extensions this extension depends on.
// The app will ensure dependencies are started before this extension.
Dependencies() []string
}
Extension represents an official Forge extension that can be registered with an App. Extensions have full access to the framework and are first-party, trusted components.
Extensions follow a standard lifecycle:
- Register(app) - Register services with DI container
- Start(ctx) - Start the extension
- Health(ctx) - Check extension health (called periodically)
- Stop(ctx) - Stop the extension (called during graceful shutdown)
type ExtensionConfigLoader ΒΆ
type ExtensionConfigLoader struct {
// contains filtered or unexported fields
}
ExtensionConfigLoader provides helper methods for loading extension configuration from ConfigManager with fallback to programmatic config.
Extensions can use LoadConfig to:
- Try loading from "extensions.{name}" key
- Fallback to "{name}" key (legacy/v1 compatibility)
- Use provided defaults if config not found
- Optionally fail if config is required but not found
func NewExtensionConfigLoader ΒΆ
func NewExtensionConfigLoader(app App, logger Logger) *ExtensionConfigLoader
NewExtensionConfigLoader creates a new config loader
func (*ExtensionConfigLoader) LoadConfig ΒΆ
func (l *ExtensionConfigLoader) LoadConfig( key string, target interface{}, programmaticConfig interface{}, defaults interface{}, requireConfig bool, ) error
LoadConfig loads configuration for an extension from ConfigManager.
It tries the following keys in order:
- "extensions.{key}" - Namespaced pattern (preferred)
- "{key}" - Top-level pattern (legacy/v1 compatibility)
Parameters:
- key: The config key (e.g., "cache", "mcp")
- target: Pointer to config struct to populate
- programmaticConfig: Config provided programmatically (may be partially filled)
- defaults: Default config to use if nothing found
- requireConfig: If true, returns error when config not found; if false, uses defaults
Returns error only if requireConfig=true and config not found, or if binding fails.
type ExtensionInfo ΒΆ
type ExtensionInfo = shared.ExtensionInfo
ExtensionInfo contains information about a registered extension
type ExternalDocs ΒΆ
type ExternalDocs = shared.ExternalDocs
ExternalDocs points to external documentation
type ExternalDocsDef ΒΆ
type ExternalDocsDef = router.ExternalDocsDef
ExternalDocsDef defines external documentation
type GroupConfig ΒΆ
type GroupConfig = router.GroupConfig
GroupConfig holds route group configuration
type GroupOption ΒΆ
type GroupOption = router.GroupOption
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
HTTPChannelBinding represents HTTP-specific channel configuration
type HTTPMessageBinding ΒΆ
type HTTPMessageBinding = shared.HTTPMessageBinding
HTTPMessageBinding represents HTTP-specific message configuration
type HTTPOperationBinding ΒΆ
type HTTPOperationBinding = shared.HTTPOperationBinding
HTTPOperationBinding represents HTTP-specific operation configuration
type HTTPServerBinding ΒΆ
type HTTPServerBinding = shared.HTTPServerBinding
HTTPServerBinding represents HTTP-specific server configuration
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 HealthCheck ΒΆ
type HealthCheck func(ctx context.Context) HealthResult
HealthCheck represents a single health check
type HealthChecker ΒΆ
type HealthChecker = shared.HealthChecker
HealthChecker is optional for services that provide health checks
type HealthConfig ΒΆ
type HealthConfig = shared.HealthConfig
HealthConfig configures health checks
func DefaultHealthConfig ΒΆ
func DefaultHealthConfig() HealthConfig
DefaultHealthConfig returns default health configuration
type HealthManager ΒΆ
type HealthManager = shared.HealthManager
HealthManager performs health checks across the system
func NewHealthManager ΒΆ
func NewHealthManager(config *health.HealthConfig, logger Logger, metrics shared.Metrics, container shared.Container) HealthManager
NewHealthManager creates a new health manager
func NewNoOpHealthManager ΒΆ
func NewNoOpHealthManager() HealthManager
NewNoOpHealthManager creates a no-op health manager
type HealthReport ΒΆ
type HealthReport = shared.HealthReport
HealthReport contains results of all checks
type HealthResult ΒΆ
type HealthResult = shared.HealthResult
HealthResult represents the result of a health check
type HotReloadableExtension ΒΆ
type HotReloadableExtension interface {
Extension
// Reload reloads the extension's configuration or state without restarting
Reload(ctx context.Context) error
}
HotReloadableExtension is an optional interface for extensions that support hot reload.
type LoggerConfig ΒΆ
type LoggerConfig = logger.LoggingConfig
Re-export logger interfaces for 100% v1 compatibility
type LoggingConfig ΒΆ
type LoggingConfig = logger.LoggingConfig
Re-export logger interfaces for 100% v1 compatibility
type Metrics ΒΆ
Metrics provides telemetry collection
func NewMetrics ΒΆ
func NewMetrics(config *metrics.CollectorConfig, logger Logger) Metrics
NewMetrics creates a new metrics instance
func NewNoOpMetrics ΒΆ
func NewNoOpMetrics() Metrics
NewNoOpMetrics creates a no-op metrics collector
type MetricsConfig ΒΆ
type MetricsConfig = shared.MetricsConfig
MetricsConfig configures metrics collection
func DefaultMetricsConfig ΒΆ
func DefaultMetricsConfig() MetricsConfig
DefaultMetricsConfig returns default metrics configuration
type MiddlewareFunc ΒΆ
type MiddlewareFunc = router.MiddlewareFunc
MiddlewareFunc is a convenience type for middleware functions that want to explicitly call the next handler
type ObservableExtension ΒΆ
type ObservableExtension interface {
Extension
// Metrics returns a map of metric names to values
Metrics() map[string]any
}
ObservableExtension is an optional interface for extensions that provide metrics.
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 RegisterOption ΒΆ
type RegisterOption = shared.RegisterOption
RegisterOption is a configuration option for service registration
func Scoped ΒΆ
func Scoped() RegisterOption
Scoped makes the service live for the duration of a scope
func Transient ΒΆ
func Transient() RegisterOption
Transient makes the service created on each resolve
func WithDIMetadata ΒΆ
func WithDIMetadata(key, value string) RegisterOption
WithDIMetadata adds diagnostic metadata to DI service registration
func WithDependencies ΒΆ
func WithDependencies(deps ...string) RegisterOption
WithDependencies declares explicit dependencies
func WithGroup ΒΆ
func WithGroup(group string) RegisterOption
WithGroup adds service to a named group
type RequestBody ΒΆ
type RequestBody = shared.RequestBody
RequestBody describes a single request body
type RequestBodyDef ΒΆ
type RequestBodyDef = router.RequestBodyDef
RequestBodyDef defines a request body
type ResponseSchemaDef ΒΆ
type ResponseSchemaDef = router.ResponseSchemaDef
ResponseSchemaDef defines a response schema
type RouteExtension ΒΆ
type RouteExtension = router.RouteExtension
RouteExtension represents a route-level extension (e.g., OpenAPI, custom validation) Note: This is different from app-level Extension which manages app components
type RouteOption ΒΆ
type RouteOption = router.RouteOption
RouteOption configures a route
func WithAcceptedResponse ΒΆ
func WithAcceptedResponse() RouteOption
WithAcceptedResponse creates a 202 Accepted response for async operations
func WithAsyncAPIBinding ΒΆ
func WithAsyncAPIBinding(bindingType string, binding interface{}) RouteOption
WithAsyncAPIBinding adds protocol-specific bindings bindingType: "ws" or "http" or "server" or "channel" or "operation" or "message" binding: the binding object (e.g., WebSocketChannelBinding, HTTPServerBinding)
func WithAsyncAPIChannelDescription ΒΆ
func WithAsyncAPIChannelDescription(description string) RouteOption
WithAsyncAPIChannelDescription sets the channel description
func WithAsyncAPIChannelName ΒΆ
func WithAsyncAPIChannelName(name string) RouteOption
WithAsyncAPIChannelName sets a custom channel name (overrides path-based naming)
func WithAsyncAPIChannelSummary ΒΆ
func WithAsyncAPIChannelSummary(summary string) RouteOption
WithAsyncAPIChannelSummary sets the channel summary
func WithAsyncAPIExternalDocs ΒΆ
func WithAsyncAPIExternalDocs(url, description string) RouteOption
WithAsyncAPIExternalDocs adds external documentation link
func WithAsyncAPIOperationID ΒΆ
func WithAsyncAPIOperationID(id string) RouteOption
WithAsyncAPIOperationID sets a custom operation ID for AsyncAPI
func WithAsyncAPISecurity ΒΆ
func WithAsyncAPISecurity(requirements map[string][]string) RouteOption
WithAsyncAPISecurity adds security requirements to the operation
func WithAsyncAPITags ΒΆ
func WithAsyncAPITags(tags ...string) RouteOption
WithAsyncAPITags adds tags to the AsyncAPI operation
func WithAuth ΒΆ
func WithAuth(providerNames ...string) RouteOption
WithAuth adds authentication to a route using one or more providers. Multiple providers create an OR condition - any one succeeding allows access.
Example:
router.GET("/protected", handler,
forge.WithAuth("api-key", "jwt"),
)
func WithAuthAnd ΒΆ
func WithAuthAnd(providerNames ...string) RouteOption
WithAuthAnd requires ALL specified providers to succeed (AND condition). This is useful for multi-factor authentication or combining auth methods.
Example:
router.GET("/high-security", handler,
forge.WithAuthAnd("api-key", "mfa"),
)
func WithBatchResponse ΒΆ
func WithBatchResponse(itemType interface{}, statusCode int) RouteOption
WithBatchResponse creates a response for batch operations
func WithCallback ΒΆ
func WithCallback(config CallbackConfig) RouteOption
WithCallback adds a callback definition to a route
func WithCorrelationID ΒΆ
func WithCorrelationID(location, description string) RouteOption
WithCorrelationID adds correlation ID configuration for request-reply patterns location: runtime expression like "$message.header#/correlationId" description: description of the correlation ID
func WithCreatedResponse ΒΆ
func WithCreatedResponse(resourceType interface{}) RouteOption
WithCreatedResponse creates a 201 Created response
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
func WithExtension ΒΆ
func WithExtension(name string, ext Extension) RouteOption
func WithExternalDocs ΒΆ
func WithExternalDocs(description, url string) RouteOption
WithExternalDocs adds external documentation link
func WithFileUploadResponse ΒΆ
func WithFileUploadResponse(statusCode int) RouteOption
WithFileUploadResponse creates a response for file upload success
func WithHeaderSchema ΒΆ
func WithHeaderSchema(schemaType interface{}) RouteOption
WithHeaderSchema sets the header parameters schema for OpenAPI generation
func WithListResponse ΒΆ
func WithListResponse(itemType interface{}, statusCode int) RouteOption
WithListResponse creates a simple list response (array of items)
func WithMessageContentType ΒΆ
func WithMessageContentType(contentType string) RouteOption
WithMessageContentType sets the content type for messages Default is "application/json"
func WithMessageExample ΒΆ
func WithMessageExample(direction, name string, example interface{}) RouteOption
WithMessageExample adds a single message example
func WithMessageExamples ΒΆ
func WithMessageExamples(direction string, examples map[string]interface{}) RouteOption
WithMessageExamples adds message examples for send/receive direction: "send" or "receive" examples: map of example name to example value
func WithMessageHeaders ΒΆ
func WithMessageHeaders(headersSchema interface{}) RouteOption
WithMessageHeaders defines headers schema for messages headersSchema: Go type with header:"name" tags
func WithMetadata ΒΆ
func WithMetadata(key string, value any) RouteOption
func WithMiddleware ΒΆ
func WithMiddleware(mw ...Middleware) RouteOption
func WithNoContentResponse ΒΆ
func WithNoContentResponse() RouteOption
WithNoContentResponse creates a 204 No Content response
func WithORPCExclude ΒΆ
func WithORPCExclude() RouteOption
WithORPCExclude excludes this route from oRPC auto-exposure. Use this to prevent specific routes from being exposed as JSON-RPC methods.
Example:
router.GET("/internal/debug", debugHandler,
forge.WithORPCExclude(),
)
func WithORPCMethod ΒΆ
func WithORPCMethod(methodName string) RouteOption
WithORPCMethod sets a custom JSON-RPC method name for this route. By default, method names are generated from the HTTP method and path.
Example:
router.GET("/users/:id", getUserHandler,
forge.WithORPCMethod("user.get"),
)
func WithORPCParams ΒΆ
func WithORPCParams(schema any) RouteOption
WithORPCParams sets the params schema for OpenRPC schema generation. The schema should be a struct or map describing the expected parameters.
Example:
type UserGetParams struct {
ID string `json:"id"`
}
router.GET("/users/:id", getUserHandler,
forge.WithORPCParams(&orpc.ParamsSchema{
Type: "object",
Properties: map[string]*orpc.PropertySchema{
"id": {Type: "string", Description: "User ID"},
},
Required: []string{"id"},
}),
)
func WithORPCPrimaryResponse ΒΆ
func WithORPCPrimaryResponse(statusCode int) RouteOption
WithORPCPrimaryResponse sets which response status code should be used as the primary oRPC result schema when multiple success responses (200, 201, etc.) are defined. This is useful when you have both 200 and 201 responses and want to explicitly choose one.
By default, oRPC uses method-aware selection:
- POST: Prefers 201, then 200
- GET: Prefers 200
- PUT/PATCH/DELETE: Prefers 200
Example:
router.POST("/users", createUserHandler,
forge.WithResponseSchema(200, "Updated user", UserResponse{}),
forge.WithResponseSchema(201, "Created user", UserResponse{}),
forge.WithORPCPrimaryResponse(200), // Explicitly use 200
)
func WithORPCResult ΒΆ
func WithORPCResult(schema any) RouteOption
WithORPCResult sets the result schema for OpenRPC schema generation. The schema should be a struct or map describing the expected result.
Example:
router.GET("/users/:id", getUserHandler,
forge.WithORPCResult(&orpc.ResultSchema{
Type: "object",
Description: "User details",
}),
)
func WithORPCTags ΒΆ
func WithORPCTags(tags ...string) RouteOption
WithORPCTags adds custom tags for OpenRPC schema organization. These tags are used in addition to the route's regular tags.
Example:
router.GET("/users/:id", getUserHandler,
forge.WithORPCTags("users", "read"),
)
func WithOperationID ΒΆ
func WithOperationID(id string) RouteOption
func WithPaginatedResponse ΒΆ
func WithPaginatedResponse(itemType interface{}, statusCode int) RouteOption
WithPaginatedResponse creates a route option for paginated list responses
func WithParameter ΒΆ
func WithParameter(name, in, description string, required bool, example interface{}) RouteOption
WithParameter adds a parameter definition
func WithQuerySchema ΒΆ
func WithQuerySchema(schemaType interface{}) RouteOption
WithQuerySchema sets the query parameters schema for OpenAPI generation
func WithRequestBody ΒΆ
func WithRequestBody(description string, required bool, example interface{}) RouteOption
WithRequestBody adds request body documentation
func WithRequestBodySchema ΒΆ
func WithRequestBodySchema(schemaOrType interface{}) RouteOption
WithRequestBodySchema sets only the request body schema for OpenAPI generation. Use this for explicit body-only schemas when you need separate schemas for different parts.
func WithRequestContentTypes ΒΆ
func WithRequestContentTypes(types ...string) RouteOption
WithRequestContentTypes specifies the content types for request body
func WithRequestExample ΒΆ
func WithRequestExample(name string, example interface{}) RouteOption
WithRequestExample adds an example for the request body
func WithRequestSchema ΒΆ
func WithRequestSchema(schemaOrType interface{}) RouteOption
WithRequestSchema sets the unified request schema for OpenAPI generation. This is the recommended approach that automatically classifies struct fields 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.
func WithRequiredAuth ΒΆ
func WithRequiredAuth(providerName string, scopes ...string) RouteOption
WithRequiredAuth adds authentication with required scopes/permissions. The specified provider must succeed AND the auth context must have all required scopes.
Example:
router.POST("/admin/users", handler,
forge.WithRequiredAuth("jwt", "write:users", "admin"),
)
func WithResponse ΒΆ
func WithResponse(code int, description string, example interface{}) RouteOption
WithResponse adds a response definition to the route
func WithResponseContentTypes ΒΆ
func WithResponseContentTypes(types ...string) RouteOption
WithResponseContentTypes specifies the content types for response body
func WithResponseExample ΒΆ
func WithResponseExample(statusCode int, name string, example interface{}) RouteOption
WithResponseExample adds an example for a specific response status code
func WithResponseSchema ΒΆ
func WithResponseSchema(statusCode int, description string, schemaOrType interface{}) RouteOption
WithResponseSchema sets a response schema for OpenAPI generation
func WithSSEMessage ΒΆ
func WithSSEMessage(eventName string, schema interface{}) RouteOption
WithSSEMessage defines a single message schema for SSE endpoints eventName: the SSE event name (e.g., "message", "update", "notification") schema: the message schema
func WithSSEMessages ΒΆ
func WithSSEMessages(messageSchemas map[string]interface{}) RouteOption
WithSSEMessages defines message schemas for SSE endpoints messageSchemas: map of event names to their schemas SSE is receive-only (server -> client), so action is always "receive"
func WithSchemaRef ΒΆ
func WithSchemaRef(name string, schema interface{}) RouteOption
WithSchemaRef adds a schema reference to components
func WithSecurity ΒΆ
func WithSecurity(schemes ...string) RouteOption
WithSecurity sets security requirements for a route
func WithServerProtocol ΒΆ
func WithServerProtocol(serverNames ...string) RouteOption
WithServerProtocol specifies which servers this operation should be available on serverNames: list of server names from AsyncAPIConfig.Servers
func WithStandardRESTResponses ΒΆ
func WithStandardRESTResponses(resourceType interface{}) RouteOption
WithStandardRESTResponses adds standard REST CRUD responses for a resource
func WithStrictValidation ΒΆ
func WithStrictValidation() RouteOption
WithStrictValidation enables strict validation (validates both request and response)
func WithSummary ΒΆ
func WithSummary(summary string) RouteOption
func WithTags ΒΆ
func WithTags(tags ...string) RouteOption
func WithTimeout ΒΆ
func WithTimeout(d time.Duration) RouteOption
func WithValidation ΒΆ
func WithValidation(enabled bool) RouteOption
WithValidation adds validation middleware to a route
func WithValidationErrorResponse ΒΆ
func WithValidationErrorResponse() RouteOption
WithValidationErrorResponse adds a 422 Unprocessable Entity response for validation errors
func WithWebSocketMessages ΒΆ
func WithWebSocketMessages(sendSchema, receiveSchema interface{}) RouteOption
WithWebSocketMessages defines send/receive message schemas for WebSocket endpoints sendSchema: messages that the client sends to the server (action: send) receiveSchema: messages that the server sends to the client (action: receive)
func WithWebhook ΒΆ
func WithWebhook(name string, operation *CallbackOperation) RouteOption
WithWebhook adds a webhook definition to the OpenAPI spec
type Router ΒΆ
Router provides HTTP routing with multiple backend support
func NewRouter ΒΆ
func NewRouter(opts ...RouterOption) Router
NewRouter creates a new router with options
type RouterAdapter ΒΆ
type RouterAdapter = router.RouterAdapter
RouterAdapter wraps a routing backend
func NewBunRouterAdapter ΒΆ
func NewBunRouterAdapter() RouterAdapter
NewBunRouterAdapter creates a BunRouter adapter (default)
type RouterOption ΒΆ
type RouterOption = router.RouterOption
RouterOption configures the router
func WithAsyncAPI ΒΆ
func WithAsyncAPI(config AsyncAPIConfig) RouterOption
WithAsyncAPI enables AsyncAPI 3.0.0 spec generation
func WithContainer ΒΆ
func WithContainer(container Container) RouterOption
func WithErrorHandler ΒΆ
func WithErrorHandler(handler ErrorHandler) RouterOption
func WithHealth ΒΆ
func WithHealth(config HealthConfig) RouterOption
WithHealth enables health checks
func WithLogger ΒΆ
func WithLogger(logger Logger) RouterOption
func WithMetrics ΒΆ
func WithMetrics(config 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 Scope ΒΆ
Scope represents a lifetime scope for scoped services Typically used for HTTP requests or other bounded operations
type SecurityRequirement ΒΆ
type SecurityRequirement = shared.SecurityRequirement
SecurityRequirement lists required security schemes
type SecurityScheme ΒΆ
type SecurityScheme = shared.SecurityScheme
SecurityScheme defines a security scheme
type Service ΒΆ
Service is the standard interface for managed services Container auto-detects and calls these methods
type ServiceError ΒΆ
type ServiceError = errors.ServiceError
Re-export error types for backward compatibility
type ServiceInfo ΒΆ
type ServiceInfo = shared.ServiceInfo
ServiceInfo contains diagnostic information
type SourceEventHandler ΒΆ
type SourceEventHandler = config.SourceEventHandler
Configuration Sources
type StreamConfig ΒΆ
type StreamConfig = router.StreamConfig
StreamConfig configures streaming behavior
func DefaultStreamConfig ΒΆ
func DefaultStreamConfig() StreamConfig
DefaultStreamConfig returns default streaming configuration
type SugarLogger ΒΆ
type SugarLogger = logger.SugarLogger
Re-export logger interfaces for 100% v1 compatibility
type ValidationError ΒΆ
type ValidationError = router.ValidationError
ValidationError represents a single field validation error
type ValidationErrors ΒΆ
type ValidationErrors = router.ValidationErrors
ValidationErrors is a collection of validation errors
func NewValidationErrors ΒΆ
func NewValidationErrors() *ValidationErrors
NewValidationErrors creates a new ValidationErrors instance
type WebSocketChannelBinding ΒΆ
type WebSocketChannelBinding = shared.WebSocketChannelBinding
WebSocketChannelBinding represents WebSocket-specific channel configuration
type WebSocketHandler ΒΆ
type WebSocketHandler = router.WebSocketHandler
WebSocketHandler handles WebSocket connections
type WebSocketMessageBinding ΒΆ
type WebSocketMessageBinding = shared.WebSocketMessageBinding
WebSocketMessageBinding represents WebSocket-specific message configuration
type WebSocketOperationBinding ΒΆ
type WebSocketOperationBinding = shared.WebSocketOperationBinding
WebSocketOperationBinding represents WebSocket-specific operation configuration
type WebSocketServerBinding ΒΆ
type WebSocketServerBinding = shared.WebSocketServerBinding
WebSocketServerBinding represents WebSocket-specific server configuration
type WebTransportConfig ΒΆ
type WebTransportConfig = router.WebTransportConfig
WebTransportConfig configures WebTransport behavior
func DefaultWebTransportConfig ΒΆ
func DefaultWebTransportConfig() WebTransportConfig
DefaultWebTransportConfig returns default WebTransport configuration
type WebTransportHandler ΒΆ
type WebTransportHandler = router.WebTransportHandler
WebTransportHandler handles WebTransport sessions
type WebTransportSession ΒΆ
type WebTransportSession = router.WebTransportSession
WebTransportSession represents a WebTransport session
type WebTransportStream ΒΆ
type WebTransportStream = router.WebTransportStream
WebTransportStream represents a WebTransport stream
Source Files
ΒΆ
- app.go
- app_impl.go
- asyncapi.go
- bunrouter.go
- config.go
- context.go
- controller.go
- di.go
- di_helpers.go
- di_opts.go
- errors.go
- extension.go
- extension_base.go
- extension_config.go
- handler.go
- health.go
- logger.go
- metrics.go
- middleware.go
- openapi.go
- router.go
- router_asyncapi.go
- router_observability.go
- router_openapi.go
- router_openapi_opts.go
- service.go
- streaming.go
Directories
ΒΆ
| Path | Synopsis |
|---|---|
|
examples/async_select
command
|
|
|
examples/enhanced_features
command
|
|
|
examples/forge_integration
command
|
|
|
examples/interactive
command
|
|
|
examples/interactive_arrows
command
|
|
|
examples/plugin
command
|
|
|
examples/simple
command
|
|
|
examples/subcommands
command
|
|
|
cmd
|
|
|
forge
command
v2/cmd/forge/main.go
|
v2/cmd/forge/main.go |
|
forge/config
v2/cmd/forge/config/loader.go
|
v2/cmd/forge/config/loader.go |
|
forge/plugins
v2/cmd/forge/plugins/build.go
|
v2/cmd/forge/plugins/build.go |
|
examples
|
|
|
ai-agents-demo
command
|
|
|
ai-demo
command
|
|
|
cache-demo
command
|
|
|
config-example
command
|
|
|
database-demo
command
|
|
|
events-demo
command
|
|
|
mcp-advanced
command
|
|
|
mcp-basic
command
|
|
|
minimal-app
command
|
|
|
observability
command
|
|
|
orpc_example
command
|
|
|
service-di
command
|
|
|
simple-extension
command
|
|
|
extensions
|
|
|
consensus/examples/basic
command
|
|
|
dashboard/examples/basic
command
|
|
|
database
Package database provides unified database access with support for SQL (Postgres, MySQL, SQLite) and NoSQL (MongoDB) databases.
|
Package database provides unified database access with support for SQL (Postgres, MySQL, SQLite) and NoSQL (MongoDB) databases. |
|
storage
Package storage provides unified object storage with support for multiple backends including local filesystem, S3, GCS, and Azure Blob Storage.
|
Package storage provides unified object storage with support for multiple backends including local filesystem, S3, GCS, and Azure Blob Storage. |
|
streaming/examples/chat
command
|
|
|
webrtc/examples/basic
command
|
|
|
features
module
|
|
|
graphql
module
|
|
|
grpc
module
|
|
|
kafka
module
|
|
|
mqtt
module
|
|
|
farp
module
|
|
|
internal
|
|