Documentation
ΒΆ
Index ΒΆ
- Constants
- Variables
- func Must[T any](c Container, name string) T
- func MustGet[T any](cm ConfigManager, key string) T
- func MustResolveReady[T any](ctx context.Context, c Container, name string) T
- func MustScope[T any](s Scope, name string) T
- func Provide[T any](c Container, name string, args ...any) error
- func ProvideWithOpts[T any](c Container, name string, opts []RegisterOption, args ...any) error
- 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 RegisterScopedWith[T any](c Container, name string, args ...any) 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 RegisterSingletonWith[T any](c Container, name string, args ...any) 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 RegisterTransientWith[T any](c Container, name string, args ...any) error
- func RegisterValue[T any](c Container, name string, instance T) error
- func Resolve[T any](c Container, name string) (T, error)
- func ResolveReady[T any](ctx context.Context, 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 AppOption
- func WithAppConfigManager(configManager ConfigManager) AppOption
- func WithAppDescription(description string) AppOption
- func WithAppEnvironment(environment string) AppOption
- func WithAppErrorHandler(handler ErrorHandler) AppOption
- func WithAppHealthConfig(config HealthConfig) AppOption
- func WithAppLogger(logger Logger) AppOption
- func WithAppMetrics(metrics Metrics) AppOption
- func WithAppMetricsConfig(config MetricsConfig) AppOption
- func WithAppName(name string) AppOption
- func WithAppRouterOptions(opts ...RouterOption) AppOption
- func WithAppVersion(version string) AppOption
- func WithConfig(config AppConfig) AppOption
- func WithConfigBaseNames(names ...string) AppOption
- func WithConfigLocalNames(names ...string) AppOption
- func WithConfigSearchPaths(paths ...string) AppOption
- func WithEnableAppScopedConfig(enabled bool) AppOption
- func WithEnableConfigAutoDiscovery(enabled bool) AppOption
- func WithEnableEnvConfig(enabled bool) AppOption
- func WithEnvOverridesFile(override bool) AppOption
- func WithEnvPrefix(prefix string) AppOption
- func WithEnvSeparator(separator string) AppOption
- func WithExtensions(extensions ...Extension) AppOption
- func WithHTTPAddress(address string) AppOption
- func WithHTTPTimeout(timeout time.Duration) AppOption
- func WithShutdownSignals(signals ...os.Signal) AppOption
- func WithShutdownTimeout(timeout time.Duration) AppOption
- 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 AutoDiscoveryConfig
- type AutoDiscoveryResult
- 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 any, programmaticConfig any, defaults any, ...) 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
- 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 Dep
- type DepMode
- type DependencySpecExtension
- type Discriminator
- type DiscriminatorConfig
- type Disposable
- type Encoding
- type EnvSourceConfig
- type EnvSourceOptions
- type ErrorHandler
- type Example
- type Extension
- type ExtensionConfigLoader
- type ExtensionInfo
- type ExternalAppConfig
- type ExternalAppExtension
- 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 WithGroupSchemaExclude() GroupOption
- func WithGroupTags(tags ...string) GroupOption
- type HTTPChannelBinding
- type HTTPError
- type HTTPMessageBinding
- type HTTPOperationBinding
- type HTTPServerBinding
- type Handler
- 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 InjectOption
- type InternalExtension
- type LazyAny
- type LazyRef
- type License
- type LifecycleHook
- type LifecycleHookOptions
- type LifecycleManager
- type LifecyclePhase
- type Link
- type LogLevel
- type Logger
- type LoggerConfig
- type LoggingConfig
- type ManagerConfig
- type Map
- type MediaType
- type MetricType
- type Metrics
- type MetricsConfig
- type Middleware
- type MiddlewareExtension
- type MiddlewareFunc
- type OAuthFlow
- type OAuthFlows
- type ObservableExtension
- type OpenAPIConfig
- type OpenAPIServer
- type OpenAPISpec
- type OpenAPITag
- type Operation
- type OptionalLazyAny
- type OptionalLazyRef
- type Parameter
- type ParameterDef
- type PathItem
- type ProviderRef
- type PureMiddleware
- type RegisterOption
- type RequestBody
- type RequestBodyDef
- type Response
- type ResponseDef
- type ResponseSchemaDef
- type RouteConfig
- type RouteExtension
- type RouteInfo
- type RouteOption
- func ExtensionRoutes(ext Extension, additionalOpts ...RouteOption) []RouteOption
- func WithAcceptedResponse() RouteOption
- func WithAsyncAPIBinding(bindingType string, binding any) RouteOption
- func WithAsyncAPIChannelDescription(description string) RouteOption
- func WithAsyncAPIChannelName(name string) RouteOption
- func WithAsyncAPIChannelSummary(summary string) RouteOption
- func WithAsyncAPIExclude() RouteOption
- func WithAsyncAPIExternalDocs(url, description string) RouteOption
- func WithAsyncAPIOperationID(id string) RouteOption
- func WithAsyncAPISecurity(requirements map[string][]string) RouteOption
- func WithAsyncAPITags(tags ...string) RouteOption
- func WithAuth(providerNames ...string) RouteOption
- func WithAuthAnd(providerNames ...string) RouteOption
- func WithBatchResponse(itemType any, statusCode int) RouteOption
- func WithCallback(config CallbackConfig) RouteOption
- func WithCorrelationID(location, description string) RouteOption
- func WithCreatedResponse(resourceType any) RouteOption
- func WithDeprecated() RouteOption
- func WithDescription(desc string) RouteOption
- func WithDiscriminator(config DiscriminatorConfig) RouteOption
- func WithErrorResponses() RouteOption
- func WithExtension(name string, ext Extension) RouteOption
- func WithExtensionExclusion(ext Extension) RouteOption
- func WithExternalDocs(description, url string) RouteOption
- func WithFileUploadResponse(statusCode int) RouteOption
- func WithHeaderSchema(schemaType any) RouteOption
- func WithListResponse(itemType any, statusCode int) RouteOption
- func WithMessageContentType(contentType string) RouteOption
- func WithMessageExample(direction, name string, example any) RouteOption
- func WithMessageExamples(direction string, examples map[string]any) RouteOption
- func WithMessageHeaders(headersSchema any) RouteOption
- func WithMetadata(key string, value any) RouteOption
- func WithMethod(method string) 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 WithOpenAPIExclude() RouteOption
- func WithOperationID(id string) RouteOption
- func WithPaginatedResponse(itemType any, statusCode int) RouteOption
- func WithParameter(name, in, description string, required bool, example any) RouteOption
- func WithQuerySchema(schemaType any) RouteOption
- func WithRequestBody(description string, required bool, example any) RouteOption
- func WithRequestBodySchema(schemaOrType any) RouteOption
- func WithRequestContentTypes(types ...string) RouteOption
- func WithRequestExample(name string, example any) RouteOption
- func WithRequestSchema(schemaOrType any) RouteOption
- func WithRequiredAuth(providerName string, scopes ...string) RouteOption
- func WithResponse(code int, description string, example any) RouteOption
- func WithResponseContentTypes(types ...string) RouteOption
- func WithResponseExample(statusCode int, name string, example any) RouteOption
- func WithResponseSchema(statusCode int, description string, schemaOrType any) RouteOption
- func WithSSEMessage(eventName string, schema any) RouteOption
- func WithSSEMessages(messageSchemas map[string]any) RouteOption
- func WithSchemaExclude() RouteOption
- func WithSchemaRef(name string, schema any) RouteOption
- func WithSecurity(schemes ...string) RouteOption
- func WithSensitiveFieldCleaning() RouteOption
- func WithServerProtocol(serverNames ...string) RouteOption
- func WithStandardRESTResponses(resourceType any) RouteOption
- func WithStrictValidation() RouteOption
- func WithSummary(summary string) RouteOption
- func WithTags(tags ...string) RouteOption
- func WithTimeout(d time.Duration) RouteOption
- func WithValidation(enabled bool) RouteOption
- func WithValidationErrorResponse() RouteOption
- func WithWebSocketMessages(sendSchema, receiveSchema any) RouteOption
- func 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 RunnableExtension
- 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 StringMap
- 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 ( // DepEager resolves the dependency immediately during service creation. DepEager = shared.DepEager // DepLazy defers resolution until the dependency is first accessed. DepLazy = shared.DepLazy // DepOptional resolves immediately but returns nil if not found. DepOptional = shared.DepOptional // DepLazyOptional combines lazy resolution with optional behavior. DepLazyOptional = shared.DepLazyOptional )
Dependency mode constants
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 Use config.ManagerKey or shared.ConfigKey for consistency.
Variables ΒΆ
var ( NewManager = config.NewManager NewSourceRegistry = config.NewSourceRegistry NewValidator = config.NewValidator NewWatcher = config.NewWatcher NewSecretsManager = config.NewSecretsManager // Environment Variable Source Constructors NewEnvSource = sources.NewEnvSource // Auto-Discovery Functions DiscoverAndLoadConfigs = config.DiscoverAndLoadConfigs DefaultAutoDiscoveryConfig = config.DefaultAutoDiscoveryConfig )
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 NewBeautifulLogger = logger.NewBeautifulLogger 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 = errors.New("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 MustResolveReady ΒΆ added in v0.8.0
MustResolveReady resolves or panics, ensuring the service is started first. Use only during startup/registration phase.
func Provide ΒΆ added in v0.8.0
Provide registers a service with typed dependency injection. It accepts InjectOption arguments followed by a factory function.
The factory function receives the resolved dependencies in order and returns the service instance and an optional error.
Usage:
forge.Provide[*UserService](c, "userService",
forge.Inject[*bun.DB]("database"),
forge.Inject[Logger]("logger"),
forge.LazyInject[*Cache]("cache"),
func(db *bun.DB, logger Logger, cache *forge.LazyRef[*Cache]) (*UserService, error) {
return &UserService{db, logger, cache}, nil
},
)
func ProvideWithOpts ΒΆ added in v0.8.0
ProvideWithOpts is like Provide but accepts additional RegisterOptions.
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 RegisterScopedWith ΒΆ added in v0.8.0
RegisterScopedWith registers a scoped service with typed dependency injection. Accepts InjectOption arguments followed by a factory function.
Usage:
forge.RegisterScopedWith[*Session](c, "session",
forge.Inject[*User]("user"),
func(user *User) (*Session, error) {
return &Session{user: user}, nil
},
)
func RegisterSingleton ΒΆ
RegisterSingleton is a convenience wrapper for singleton services.
func RegisterSingletonInterface ΒΆ
func RegisterSingletonInterface[I, T any](c Container, name string, factory func(Container) (T, error)) error
RegisterSingletonInterface is a convenience wrapper.
func RegisterSingletonWith ΒΆ added in v0.8.0
RegisterSingletonWith registers a singleton service with typed dependency injection. Accepts InjectOption arguments followed by a factory function.
Usage:
forge.RegisterSingletonWith[*UserService](c, "userService",
forge.Inject[*bun.DB]("database"),
func(db *bun.DB) (*UserService, error) {
return &UserService{db: db}, nil
},
)
func RegisterTransient ΒΆ
RegisterTransient is a convenience wrapper for transient services.
func RegisterTransientInterface ΒΆ
func RegisterTransientInterface[I, T any](c Container, name string, factory func(Container) (T, error)) error
RegisterTransientInterface is a convenience wrapper.
func RegisterTransientWith ΒΆ added in v0.8.0
RegisterTransientWith registers a transient service with typed dependency injection. Accepts InjectOption arguments followed by a factory function.
Usage:
forge.RegisterTransientWith[*Request](c, "request",
forge.Inject[*Context]("ctx"),
func(ctx *Context) (*Request, error) {
return &Request{ctx: ctx}, nil
},
)
func RegisterValue ΒΆ
RegisterValue registers a pre-built instance (always singleton).
func ResolveReady ΒΆ added in v0.8.0
ResolveReady resolves a service with type safety, ensuring it and its dependencies are started first. This is useful during extension Register() phase when you need a dependency to be fully initialized before use.
Example usage in an extension's Register() method:
func (e *MyExtension) Register(app forge.App) error {
ctx := context.Background()
dbManager, err := forge.ResolveReady[*database.DatabaseManager](ctx, app.Container(), database.ManagerKey)
if err != nil {
return fmt.Errorf("database required: %w", err)
}
// dbManager is now fully started with open connections
e.redis, _ = dbManager.Redis("cache")
return nil
}
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
LifecycleManager() LifecycleManager
// 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
// Lifecycle hooks - convenience methods
RegisterHook(phase LifecyclePhase, hook LifecycleHook, opts LifecycleHookOptions) error
RegisterHookFn(phase LifecyclePhase, name string, hook LifecycleHook) 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.
func NewWithConfig ΒΆ added in v0.5.0
NewWithConfig creates a new Forge application with a complete config.
type AppConfig ΒΆ
type AppConfig struct {
// Basic info
Name string
Version string
Description string
Environment string // "development", "staging", "production"
// Components
ConfigManager ConfigManager
Logger Logger
Metrics Metrics
// 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
// Config Auto-Discovery
// If ConfigManager is not provided, these options control auto-discovery
EnableConfigAutoDiscovery bool // Enable automatic config file discovery (default: true)
ConfigSearchPaths []string // Paths to search for config files (default: current directory)
ConfigBaseNames []string // Base config file names (default: ["config.yaml", "config.yml"])
ConfigLocalNames []string // Local config file names (default: ["config.local.yaml", "config.local.yml"])
EnableAppScopedConfig bool // Enable app-scoped config extraction for monorepos (default: true)
// Environment Variable Config Sources
// These options control how environment variables are loaded as config sources
EnableEnvConfig bool // Enable loading config from environment variables (default: true)
EnvPrefix string // Prefix for environment variables (default: app name uppercase, e.g., "MYAPP_")
EnvSeparator string // Separator for nested keys in env vars (default: "_")
EnvOverridesFile bool // Whether env vars override file config values (default: true)
}
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 AppOption ΒΆ added in v0.5.0
type AppOption func(*AppConfig)
AppOption is a functional option for AppConfig.
func WithAppConfigManager ΒΆ added in v0.5.0
func WithAppConfigManager(configManager ConfigManager) AppOption
WithAppConfigManager sets the config manager.
func WithAppDescription ΒΆ added in v0.5.0
WithAppDescription sets the application description.
func WithAppEnvironment ΒΆ added in v0.5.0
WithAppEnvironment sets the application environment.
func WithAppErrorHandler ΒΆ added in v0.5.0
func WithAppErrorHandler(handler ErrorHandler) AppOption
WithAppErrorHandler sets the error handler.
func WithAppHealthConfig ΒΆ added in v0.5.0
func WithAppHealthConfig(config HealthConfig) AppOption
WithAppHealthConfig sets the health configuration.
func WithAppLogger ΒΆ added in v0.5.0
WithAppLogger sets the logger.
func WithAppMetrics ΒΆ added in v0.5.0
WithAppConfigManager sets the config manager.
func WithAppMetricsConfig ΒΆ added in v0.5.0
func WithAppMetricsConfig(config MetricsConfig) AppOption
WithAppMetricsConfig sets the metrics configuration.
func WithAppName ΒΆ added in v0.5.0
WithAppName sets the application name.
func WithAppRouterOptions ΒΆ added in v0.5.0
func WithAppRouterOptions(opts ...RouterOption) AppOption
WithAppRouterOptions sets the router options.
func WithAppVersion ΒΆ added in v0.5.0
WithAppVersion sets the application version.
func WithConfig ΒΆ added in v0.5.0
WithConfig replaces the entire config.
func WithConfigBaseNames ΒΆ added in v0.5.0
WithConfigBaseNames sets the config base names.
func WithConfigLocalNames ΒΆ added in v0.5.0
WithConfigLocalNames sets the config local names.
func WithConfigSearchPaths ΒΆ added in v0.5.0
WithConfigSearchPaths sets the config search paths.
func WithEnableAppScopedConfig ΒΆ added in v0.5.0
WithEnableAppScopedConfig enables or disables app-scoped config.
func WithEnableConfigAutoDiscovery ΒΆ added in v0.5.0
WithEnableConfigAutoDiscovery enables or disables config auto-discovery.
func WithEnableEnvConfig ΒΆ added in v0.8.3
WithEnableEnvConfig enables or disables environment variable config source.
func WithEnvOverridesFile ΒΆ added in v0.8.3
WithEnvOverridesFile controls whether environment variables override file config values. Default is true (env vars take precedence over file config).
func WithEnvPrefix ΒΆ added in v0.8.3
WithEnvPrefix sets the prefix for environment variables. If not set, defaults to the app name in uppercase with trailing underscore.
func WithEnvSeparator ΒΆ added in v0.8.3
WithEnvSeparator sets the separator for nested keys in environment variables. Default is "_".
func WithExtensions ΒΆ added in v0.5.0
WithExtensions sets the extensions.
func WithHTTPAddress ΒΆ added in v0.5.0
WithHTTPAddress sets the HTTP address.
func WithHTTPTimeout ΒΆ added in v0.5.0
WithHTTPTimeout sets the HTTP timeout.
func WithShutdownSignals ΒΆ added in v0.5.0
WithShutdownSignals sets the shutdown signals.
func WithShutdownTimeout ΒΆ added in v0.5.0
WithShutdownTimeout sets the shutdown timeout.
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 AutoDiscoveryConfig ΒΆ added in v0.8.3
type AutoDiscoveryConfig = config.AutoDiscoveryConfig
Auto-Discovery Types.
type AutoDiscoveryResult ΒΆ added in v0.8.3
type AutoDiscoveryResult = config.AutoDiscoveryResult
Auto-Discovery Types.
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 any, programmaticConfig any, defaults any, 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) Name ΒΆ
func (e *BaseExtension) Name() string
Name returns the extension name.
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 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 = 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 GetConfigManager ΒΆ added in v0.5.0
func GetConfigManager(c Container) (ConfigManager, error)
GetConfigManager resolves the config manager from the container Returns the config manager instance and an error if resolution fails.
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 Connection ΒΆ
type Connection = router.Connection
Connection represents a WebSocket connection.
type Controller ΒΆ
type Controller interface {
// Name returns the controller identifier
Name() string
// Routes registers routes on the router
Routes(r Router) error
}
Controller organizes related routes.
type ControllerWithDependencies ΒΆ
type ControllerWithDependencies interface {
Controller
Dependencies() []string
}
ControllerWithDependencies declares dependencies for ordering.
type ControllerWithMiddleware ΒΆ
type ControllerWithMiddleware interface {
Controller
Middleware() []Middleware
}
ControllerWithMiddleware applies middleware to all routes.
type ControllerWithPrefix ΒΆ
type ControllerWithPrefix interface {
Controller
Prefix() string
}
ControllerWithPrefix sets a path prefix for all routes.
type ControllerWithTags ΒΆ
type ControllerWithTags interface {
Controller
Tags() []string
}
ControllerWithTags adds metadata tags to all routes.
type 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 Dep ΒΆ added in v0.8.0
Dep represents a dependency specification for a service. It describes what service is needed and how it should be resolved.
func DepEagerSpec ΒΆ added in v0.8.0
DepEagerSpec creates an eager dependency specification. The dependency is resolved immediately and fails if not found.
func DepLazyOptionalSpec ΒΆ added in v0.8.0
DepLazyOptionalSpec creates a lazy optional dependency specification. The dependency is resolved on first access and returns nil if not found.
func DepLazySpec ΒΆ added in v0.8.0
DepLazySpec creates a lazy dependency specification. The dependency is resolved on first access.
func DepOptionalSpec ΒΆ added in v0.8.0
DepOptionalSpec creates an optional dependency specification. The dependency is resolved immediately but returns nil if not found.
type DependencySpecExtension ΒΆ added in v0.8.0
type DependencySpecExtension interface {
Extension
// DepsSpec returns the list of dependency specifications for this extension.
// Each Dep can specify the dependency mode (eager, lazy, optional).
DepsSpec() []Dep
}
DependencySpecExtension is an optional interface for extensions that want to declare their dependencies with full Dep specs (lazy, optional, etc.). If an extension implements this interface, DepsSpec() takes precedence over Dependencies().
Example:
func (e *QueueExtension) DepsSpec() []forge.Dep {
if e.config.UseDatabaseRedis {
return []forge.Dep{
forge.Eager("database"), // Need database fully ready
}
}
return nil
}
type Discriminator ΒΆ
type Discriminator = shared.Discriminator
Discriminator supports polymorphism.
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 EnvSourceConfig ΒΆ added in v0.8.3
type EnvSourceConfig = sources.EnvSourceConfig
Environment Variable Source Types.
type EnvSourceOptions ΒΆ added in v0.8.3
type EnvSourceOptions = sources.EnvSourceOptions
Environment Variable Source Types.
type ErrorHandler ΒΆ
type ErrorHandler = shared.ErrorHandler
ErrorHandler handles errors from handlers.
func NewDefaultErrorHandler ΒΆ
func NewDefaultErrorHandler(l Logger) ErrorHandler
NewDefaultErrorHandler creates a default error handler.
type Extension ΒΆ
type Extension interface {
// Name returns the unique name of the extension
Name() string
// Version returns the semantic version of the extension
Version() string
// Description returns a human-readable description
Description() string
// 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 any, programmaticConfig any, defaults any, 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 ExternalAppConfig ΒΆ added in v0.4.0
type ExternalAppConfig struct {
// Name is a unique identifier for this external app
Name string
// Command is the executable to run
Command string
// Args are command-line arguments
Args []string
// Env are additional environment variables (key=value pairs)
Env []string
// Dir is the working directory (empty = inherit from parent)
Dir string
// RestartOnFailure enables automatic restart if the process crashes
RestartOnFailure bool
// RestartDelay is the delay before restarting (default: 5s)
RestartDelay time.Duration
// ShutdownTimeout is the maximum time to wait for graceful shutdown (default: 30s)
ShutdownTimeout time.Duration
// ForwardOutput forwards stdout/stderr to the app's stdout/stderr
ForwardOutput bool
// LogOutput logs stdout/stderr through the app's logger
LogOutput bool
}
ExternalAppConfig configures an external application.
func DefaultExternalAppConfig ΒΆ added in v0.4.0
func DefaultExternalAppConfig() ExternalAppConfig
DefaultExternalAppConfig returns default configuration.
type ExternalAppExtension ΒΆ added in v0.4.0
type ExternalAppExtension struct {
*BaseExtension
// contains filtered or unexported fields
}
ExternalAppExtension manages external applications as Forge extensions. It implements RunnableExtension and handles process lifecycle, monitoring, and graceful shutdown.
Example:
func NewRedisExtension() forge.Extension {
return forge.NewExternalAppExtension(forge.ExternalAppConfig{
Name: "redis-server",
Command: "redis-server",
Args: []string{"--port", "6379"},
})
}
func NewExternalAppExtension ΒΆ added in v0.4.0
func NewExternalAppExtension(config ExternalAppConfig) *ExternalAppExtension
NewExternalAppExtension creates a new external app extension.
func (*ExternalAppExtension) Health ΒΆ added in v0.4.0
func (e *ExternalAppExtension) Health(ctx context.Context) error
Health checks if the external app is healthy.
func (*ExternalAppExtension) IsRunning ΒΆ added in v0.4.0
func (e *ExternalAppExtension) IsRunning() bool
IsRunning returns whether the external app is running.
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 WithGroupSchemaExclude ΒΆ added in v0.7.0
func WithGroupSchemaExclude() GroupOption
WithGroupSchemaExclude excludes all routes in this group from schema generation (OpenAPI, AsyncAPI, and oRPC).
This is useful for internal/debug/admin route groups that shouldn't appear in public API documentation.
Example:
// Create an internal admin group
adminGroup := router.Group("/admin", forge.WithGroupSchemaExclude())
adminGroup.GET("/users", listUsers)
adminGroup.DELETE("/cache", flushCache)
// All routes in this group are excluded from schemas
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 GetHealthManager ΒΆ added in v0.5.0
func GetHealthManager(c Container) (HealthManager, error)
GetHealthManager resolves the health manager from the container Returns the health manager instance and an error if resolution fails.
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 HealthStatus ΒΆ
type HealthStatus = shared.HealthStatus
HealthStatus represents overall health.
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 InjectOption ΒΆ added in v0.8.0
type InjectOption = di.InjectOption
InjectOption represents a dependency injection option with type information.
func Inject ΒΆ added in v0.8.0
func Inject[T any](name string) InjectOption
Inject creates an eager injection option for a dependency. The dependency is resolved immediately when the service is created.
Usage:
forge.Provide(c, "userService",
forge.Inject[*bun.DB]("database"),
func(db *bun.DB) (*UserService, error) { ... },
)
func LazyInject ΒΆ added in v0.8.0
func LazyInject[T any](name string) InjectOption
LazyInject creates a lazy injection option for a dependency. The dependency is resolved on first access via Lazy[T].Get().
func LazyOptionalInject ΒΆ added in v0.8.0
func LazyOptionalInject[T any](name string) InjectOption
LazyOptionalInject creates a lazy optional injection option. The dependency is resolved on first access and returns nil if not found.
func OptionalInject ΒΆ added in v0.8.0
func OptionalInject[T any](name string) InjectOption
OptionalInject creates an optional injection option for a dependency. The dependency is resolved immediately but returns nil if not found.
func ProviderInject ΒΆ added in v0.8.0
func ProviderInject[T any](name string) InjectOption
ProviderInject creates an injection option for a transient dependency provider.
type InternalExtension ΒΆ added in v0.7.0
type InternalExtension = router.InternalExtension
InternalExtension is re-exported from router package for convenience
type LazyAny ΒΆ added in v0.8.0
LazyAny is a non-generic lazy wrapper used with LazyInject. Use this type in your factory function when using LazyInject[T].
type LazyRef ΒΆ added in v0.8.0
LazyRef wraps a dependency that is resolved on first access. This is useful for breaking circular dependencies or deferring resolution of expensive services until they're actually needed.
type LifecycleHook ΒΆ added in v0.4.0
LifecycleHook is a function called during a lifecycle phase Hooks receive the App instance and a context for cancellation.
type LifecycleHookOptions ΒΆ added in v0.4.0
type LifecycleHookOptions struct {
// Name is a unique identifier for this hook (for logging/debugging)
Name string
// Priority determines execution order (higher priority runs first)
// Default: 0
Priority int
// ContinueOnError determines if subsequent hooks run if this hook fails
// Default: false (stop on error)
ContinueOnError bool
}
LifecycleHookOptions configures a lifecycle hook.
func DefaultLifecycleHookOptions ΒΆ added in v0.4.0
func DefaultLifecycleHookOptions(name string) LifecycleHookOptions
DefaultLifecycleHookOptions returns default hook options.
type LifecycleManager ΒΆ added in v0.4.0
type LifecycleManager interface {
// RegisterHook registers a hook for a specific lifecycle phase
RegisterHook(phase LifecyclePhase, hook LifecycleHook, opts LifecycleHookOptions) error
// RegisterHookFn is a convenience method to register a hook with default options
RegisterHookFn(phase LifecyclePhase, name string, hook LifecycleHook) error
// ExecuteHooks executes all hooks for a given phase
ExecuteHooks(ctx context.Context, phase LifecyclePhase, app App) error
// GetHooks returns all hooks for a given phase (for inspection)
GetHooks(phase LifecyclePhase) []LifecycleHookOptions
// RemoveHook removes a hook by name
RemoveHook(phase LifecyclePhase, name string) error
// ClearHooks removes all hooks for a given phase
ClearHooks(phase LifecyclePhase)
}
LifecycleManager manages lifecycle hooks.
func NewLifecycleManager ΒΆ added in v0.4.0
func NewLifecycleManager(logger Logger) LifecycleManager
NewLifecycleManager creates a new lifecycle manager.
type LifecyclePhase ΒΆ added in v0.4.0
type LifecyclePhase string
LifecyclePhase represents a phase in the application lifecycle.
const ( // PhaseBeforeStart is called before the app starts (before extensions register). PhaseBeforeStart LifecyclePhase = "before_start" // PhaseAfterRegister is called after extensions register but before they start. PhaseAfterRegister LifecyclePhase = "after_register" // PhaseAfterStart is called after the app starts (after all extensions start). PhaseAfterStart LifecyclePhase = "after_start" // PhaseBeforeRun is called before the HTTP server starts listening. PhaseBeforeRun LifecyclePhase = "before_run" // PhaseAfterRun is called after the HTTP server starts (in a goroutine, non-blocking). PhaseAfterRun LifecyclePhase = "after_run" // PhaseBeforeStop is called before the app stops (before graceful shutdown). PhaseBeforeStop LifecyclePhase = "before_stop" // PhaseAfterStop is called after the app stops (after all extensions stop). PhaseAfterStop LifecyclePhase = "after_stop" )
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 Map ΒΆ added in v0.3.0
Map is a convenience alias for map[string]interface{} Used for JSON responses and generic data structures.
Example:
app.Router().GET("/api/users", func(c Context) error {
return c.JSON(200, Map{
"users": []string{"alice", "bob"},
"count": 2,
"success": true,
})
})
type Metrics ΒΆ
Metrics provides telemetry collection.
func GetMetrics ΒΆ added in v0.5.0
GetMetrics resolves the metrics from the container Returns the metrics instance and an error if resolution fails.
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 MiddlewareExtension ΒΆ added in v0.4.0
type MiddlewareExtension interface {
Extension
// Middlewares returns middleware functions to be applied globally.
// These are applied in the order returned, after extension registration
// but before routes are fully initialized.
Middlewares() []Middleware
}
MiddlewareExtension is an optional interface for extensions that provide global middleware.
Global middleware is applied to ALL routes in the application after extensions are registered but before the router starts accepting requests. Middleware is applied in the order extensions are registered, and in the order they are returned from Middlewares().
Example:
type MyExtension struct {
*forge.BaseExtension
}
func (e *MyExtension) Middlewares() []forge.Middleware {
return []forge.Middleware{
e.authMiddleware(),
e.loggingMiddleware(),
}
}
Best Practices:
- Keep middleware lightweight and fast
- Avoid blocking operations in middleware
- Use path exclusions for health checks and public endpoints
- Consider middleware order carefully
- Log when middlewares are applied for debugging
- Provide configuration to enable/disable middleware
Security Considerations:
- Validate all inputs in middleware
- Don't leak sensitive information in errors
- Be aware of middleware execution order
- Use appropriate timeouts
- Implement rate limiting if needed
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 OptionalLazyAny ΒΆ added in v0.8.0
type OptionalLazyAny = di.OptionalLazyAny
OptionalLazyAny is a non-generic optional lazy wrapper used with LazyOptionalInject. Use this type in your factory function when using LazyOptionalInject[T].
type OptionalLazyRef ΒΆ added in v0.8.0
type OptionalLazyRef[T any] = di.OptionalLazy[T]
OptionalLazyRef wraps an optional dependency that is resolved on first access. Returns nil without error if the dependency is not found.
func NewOptionalLazyRef ΒΆ added in v0.8.0
func NewOptionalLazyRef[T any](c Container, name string) *OptionalLazyRef[T]
NewOptionalLazyRef creates a new optional lazy dependency wrapper.
type ProviderRef ΒΆ added in v0.8.0
ProviderRef wraps a dependency that creates new instances on each access. This is useful for transient dependencies where a fresh instance is needed each time.
func NewProviderRef ΒΆ added in v0.8.0
func NewProviderRef[T any](c Container, name string) *ProviderRef[T]
NewProviderRef creates a new provider for transient dependencies.
type PureMiddleware ΒΆ added in v0.5.0
type PureMiddleware = router.PureMiddleware
PureMiddleware wraps HTTP handlers.
func FromMiddleware ΒΆ added in v0.5.0
func FromMiddleware(m Middleware) PureMiddleware
FromHTTPMiddleware converts a legacy http.Handler middleware to a ForgeMiddleware This allows existing http.Handler middlewares to work with forge handlers.
func ToPureMiddleware ΒΆ added in v0.5.0
func ToPureMiddleware(m Middleware, container 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.
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 Singleton ΒΆ
func Singleton() RegisterOption
Singleton makes the service a singleton (default).
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 ExtensionRoutes ΒΆ added in v0.7.0
func ExtensionRoutes(ext Extension, additionalOpts ...RouteOption) []RouteOption
ExtensionRoutes returns route options that automatically apply schema exclusion based on whether the extension implements InternalExtension.
This is a convenience function for extensions registering multiple routes.
Example:
func (e *DebugExtension) Start(ctx context.Context) error {
router := e.app.Router()
opts := forge.ExtensionRoutes(e)
router.GET("/debug/status", statusHandler, opts...)
router.GET("/debug/metrics", metricsHandler, opts...)
return nil
}
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 WithAsyncAPIExclude ΒΆ added in v0.7.0
func WithAsyncAPIExclude() RouteOption
WithAsyncAPIExclude excludes this route from AsyncAPI schema generation. Use this to prevent WebSocket/SSE routes from appearing in AsyncAPI documentation.
Example:
router.WebSocket("/internal/debug-stream", debugStreamHandler,
forge.WithAsyncAPIExclude(),
)
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.
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 WithExtensionExclusion ΒΆ added in v0.7.0
func WithExtensionExclusion(ext Extension) RouteOption
WithExtensionExclusion checks if an extension implements InternalExtension and automatically excludes its routes from schema generation if needed.
This is a helper function for extensions to use when registering routes.
Example:
func (e *DebugExtension) Start(ctx context.Context) error {
router := e.app.Router()
opts := forge.WithExtensionExclusion(e)
router.GET("/debug/status", statusHandler, opts)
router.GET("/debug/metrics", metricsHandler, opts)
return nil
}
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.
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.
Example:
// Default GET behavior
router.SSE("/events", handler)
// Override to POST
router.SSE("/events", handler, forge.WithMethod(http.MethodPost))
// POST SSE with request body
router.EventStream("/stream", streamHandler,
forge.WithMethod(http.MethodPost),
forge.WithTags("streaming"),
)
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 WithOpenAPIExclude ΒΆ added in v0.7.0
func WithOpenAPIExclude() RouteOption
WithOpenAPIExclude excludes this route from OpenAPI schema generation. Use this to prevent specific routes from appearing in OpenAPI documentation.
Example:
router.GET("/internal/health", healthHandler,
forge.WithOpenAPIExclude(),
)
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.
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.
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 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 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 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 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 a response schema for OpenAPI generation.
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 WithSchemaExclude ΒΆ added in v0.7.0
func WithSchemaExclude() RouteOption
WithSchemaExclude excludes this route from all schema generation (OpenAPI, AsyncAPI, oRPC). This is a convenience method that combines all exclusion options.
Example:
router.GET("/internal/debug", debugHandler,
forge.WithSchemaExclude(),
)
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 before JSON serialization:
- sensitive:"true" -> set to zero value (empty string, 0, nil)
- sensitive:"redact" -> set to "[REDACTED]"
- sensitive:"mask:***" -> set to custom mask "***"
Example:
type UserResponse struct {
ID string `json:"id"`
Password string `json:"password" sensitive:"true"`
APIKey string `json:"api_key" sensitive:"redact"`
Token string `json:"token" sensitive:"mask:***"`
}
router.GET("/user", handler, forge.WithSensitiveFieldCleaning())
func WithServerProtocol ΒΆ
func WithServerProtocol(serverNames ...string) RouteOption
WithServerProtocol specifies which servers this operation should be available on serverNames: list of server names from AsyncAPIConfig.Servers.
func WithStandardRESTResponses ΒΆ
func WithStandardRESTResponses(resourceType any) RouteOption
WithStandardRESTResponses adds standard REST CRUD responses for a resource.
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 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 GetRouter ΒΆ added in v0.5.0
GetRouter resolves the router from the container Returns the router instance and an error if resolution fails.
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 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 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 RunnableExtension ΒΆ added in v0.4.0
type RunnableExtension interface {
Extension
// Run starts the extension's long-running processes.
// This is called during PhaseAfterRun, after the HTTP server starts.
// Run should be non-blocking - start goroutines or external processes and return.
Run(ctx context.Context) error
// Shutdown gracefully stops the extension's long-running processes.
// This is called during PhaseBeforeStop, before the app shuts down.
// Implementations should respect the context deadline for graceful shutdown.
Shutdown(ctx context.Context) error
}
RunnableExtension is an optional interface for extensions that need to run long-running processes (goroutines, external apps, workers) alongside the app.
Extensions implementing this interface will have their Run() method called automatically during the PhaseAfterRun lifecycle phase, and their Shutdown() method called during PhaseBeforeStop.
This provides a standardized way to manage external processes, background workers, and other long-running tasks without manually registering lifecycle hooks.
Example usage:
type WorkerExtension struct {
*forge.BaseExtension
workerDone chan struct{}
}
func (e *WorkerExtension) Run(ctx context.Context) error {
e.Logger().Info("starting background worker")
go e.runWorker()
return nil
}
func (e *WorkerExtension) Shutdown(ctx context.Context) error {
e.Logger().Info("stopping background worker")
close(e.workerDone)
return nil
}
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 StringMap ΒΆ added in v0.3.0
StringMap is a convenience alias for map[string]string Used for string-to-string mappings like headers, tags, or labels.
Example:
app.Router().POST("/config", func(c Context) error {
config := StringMap{
"env": "production",
"region": "us-west-2",
}
return c.JSON(200, config)
})
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
- extension_runnable.go
- handler.go
- health.go
- lifecycle.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
- types.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 |
|
forge/plugins/infra
v2/cmd/forge/plugins/infra/generator.go
|
v2/cmd/forge/plugins/infra/generator.go |
|
examples
|
|
|
ai-agents-demo
command
|
|
|
ai-demo
command
|
|
|
banner-demo
command
|
|
|
cache-demo
command
|
|
|
config-autodiscovery/single-app
command
|
|
|
config-example
command
|
|
|
context-example
command
|
|
|
database-demo
command
|
|
|
database-migration-docker
command
Package main demonstrates that the database extension with migrations can now start successfully in Docker/CI environments without panicking.
|
Package main demonstrates that the database extension with migrations can now start successfully in Docker/CI environments without panicking. |
|
events-demo
command
|
|
|
farp-auto-detection
command
|
|
|
farp-discovery-example
command
|
|
|
group_middleware_scoping
command
|
|
|
lifecycle-hooks
command
|
|
|
mcp-advanced
command
|
|
|
mcp-basic
command
|
|
|
minimal-app
command
|
|
|
observability
command
|
|
|
orpc_example
command
|
|
|
response_with_body_tag
command
|
|
|
runnable-extension
command
|
|
|
schema_exclusion
command
|
|
|
security-auto-middleware
command
|
|
|
security-example
command
|
|
|
service-di
command
|
|
|
simple-extension
command
|
|
|
sse-streaming
command
|
|
|
wildcard_routes
command
|
|
|
extensions
|
|
|
consensus/examples/basic
command
|
|
|
cron/core
Package core contains shared interfaces to avoid import cycles.
|
Package core contains shared interfaces to avoid import cycles. |
|
cron/examples
command
|
|
|
cron/register
Package register imports scheduler and storage implementations to register them.
|
Package register imports scheduler and storage implementations to register them. |
|
dashboard/examples/basic
command
|
|
|
dashboard/examples/forgeui
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. |
|
database/migrate
Package migrate provides migration management for the database extension
|
Package migrate provides migration management for the database extension |
|
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
|
|
|
graphql
module
|
|
|
grpc
module
|
|
|
kafka
module
|
|
|
mqtt
module
|
|
|
Package farp provides Forge-specific integrations for the FARP protocol.
|
Package farp provides Forge-specific integrations for the FARP protocol. |
|
examples/basic
command
|
|
|
internal
|
|