forge

package module
v1.9.5 Latest Latest
Warning

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

Go to latest
Published: Aug 9, 2026 License: MIT Imports: 28 Imported by: 96

README ¶

Forge

A Go framework for backend services, with dependency injection, an extension system, and observability built in.

Forge™ is a backend framework, and Forge Cloud™ is its AI cloud offering, maintained by XRAPH™.

Go Version Go Report Card License GitHub Stars CI

Quick start

go install github.com/xraph/forge/cmd/forge@latest
forge --version
forge init my-app
forge dev

A minimal service:

package main

import "github.com/xraph/forge"

func main() {
    app := forge.NewApp(forge.AppConfig{
        Name:        "my-app",
        Version:     "1.0.0",
        Environment: "development",
        HTTPAddress: ":8080",
    })

    router := app.Router()
    router.GET("/", func(ctx forge.Context) error {
        return ctx.JSON(200, map[string]string{
            "message": "Hello, Forge!",
        })
    })

    // Blocks until SIGINT or SIGTERM.
    app.Run()
}

Every app serves three endpoints without configuration: /_/info for application metadata, /_/metrics for Prometheus, and /_/health for health checks.

What you get

The core framework handles the parts most services need before they can do anything interesting:

  • A type-safe dependency injection container with service lifecycles
  • An HTTP router with trie-based path matching and middleware support
  • Middleware for auth, CORS, logging and rate limiting
  • Configuration from YAML, JSON or TOML, overridable by environment variables
  • Structured logging, Prometheus metrics and distributed tracing
  • Health checks that discover and report themselves
  • Graceful startup and shutdown, so SIGTERM cleans up rather than drops work

The CLI scaffolds projects, generates handlers and services, runs migrations, and serves your app with hot reload. See cli/README.md and the commands reference.

Extensions

Extensions are modules you compose into an app. Most are production ready; three are still being built.

Extension What it does
auth Multi-provider authentication (OAuth, JWT, SAML)
cache Multi-backend caching (Redis, Memcached, in-memory)
consensus Raft consensus for distributed systems
cron Distributed cron scheduling with execution history
dashboard Micro-frontend shell for admin dashboards
database SQL (Postgres, MySQL, SQLite) and MongoDB
discovery Service discovery and registry
events Event bus and event sourcing
features Feature flags and A/B testing
graphql GraphQL server with schema generation
grpc gRPC server with reflection
hls HTTP Live Streaming
kafka Apache Kafka integration
mcp Model Context Protocol
mqtt MQTT broker and client
security Security hardening for production apps
storage Object storage (S3, GCS, local)
streaming WebSocket and SSE
webrtc Peer-to-peer real-time communication
orpc ORPC transport protocol (in progress)
queue Message queue management (in progress)
search Full-text search, Elasticsearch and Typesense (in progress)

The complete catalog covers configuration for each one.

Composing an application

Extensions are declared in the app config. Services register against the container, and handlers resolve them from it:

app := forge.NewApp(forge.AppConfig{
    Name:        "my-service",
    Version:     "1.0.0",
    Environment: "production",

    Extensions: []forge.Extension{
        database.NewExtension(database.Config{
            Databases: []database.DatabaseConfig{
                {
                    Name: "primary",
                    Type: database.TypePostgres,
                    DSN:  "postgres://localhost/mydb",
                },
            },
        }),

        auth.NewExtension(auth.Config{
            Provider: "oauth2",
        }),
    },
})

forge.RegisterSingleton(app.Container(), "userService", func(c forge.Container) (*UserService, error) {
    db, err := database.GetSQL(c)
    if err != nil {
        return nil, err
    }
    logger := forge.Must[forge.Logger](c, "logger")
    return NewUserService(db, logger), nil
})

router := app.Router()
router.GET("/users/:id", getUserHandler)
router.POST("/users", createUserHandler)

app.Run()

Switching a backend is a config change rather than a code change: the same database.GetSQL(c) call works whether it resolves to Postgres or SQLite.

Documentation

Full docs are at forge.dev. Questions and ideas go in Discussions; bugs go in Issues.

Examples

The examples directory has runnable services. Some worth starting with:

Development

You need Go 1.24 or later. Make is optional but the targets below assume it.

make build          # build the CLI
make build-debug    # build with debug symbols
make release        # build for all platforms
make test           # all tests
make test-coverage  # with coverage
go test ./extensions/graphql/...
make fmt            # format
make lint           # lint
make lint-fix       # lint and fix
make security-scan  # security scan
make vuln-check     # check dependencies for known vulnerabilities
make ci             # everything CI runs

The dev server takes --watch for hot reload and --port to override the address:

forge dev --watch --port 3000

Contributing

Fork, branch, and open a pull request. Run make install-tools once, then make ci before you push.

Commits follow Conventional Commits, which the release tooling reads to decide the version bump. See CONTRIBUTING.md for the rest.

Releases

Releases run through Release Please and a GitHub Actions workflow.

Push to main with conventional commits and Release Please opens a PR carrying the version bumps and changelog. Merging that PR creates a tag, and the tag triggers the release pipeline. For a release you need to cut by hand, go to Actions > Release and run the workflow against a chosen module and version.

The pipeline builds cross-platform binaries and Docker images for the main module and CLI and publishes them to Homebrew, Scoop and NFPM through GoReleaser. Extension modules get a GitHub release and a notification to the Go module proxy. Dry-run mode validates the whole pipeline without publishing, and tests can be skipped for a hotfix that CI has already verified.

License

MIT. See LICENSE.

Acknowledgments

Built by Rex Raphael, with thanks to Bun for the SQL ORM, Uptrace for observability, and Chi, whose router shaped the design of this one.

Documentation ¶

Index ¶

Constants ¶

View Source
const (
	StreamUpsert = router.StreamUpsert
	StreamPatch  = router.StreamPatch
	StreamEvict  = router.StreamEvict
)
View Source
const (
	ChangeTypeSet    = confy.ChangeTypeSet
	ChangeTypeUpdate = confy.ChangeTypeUpdate
	ChangeTypeDelete = confy.ChangeTypeDelete
	ChangeTypeReload = confy.ChangeTypeReload
)

Constants.

View Source
const (
	ValidationModePermissive = confy.ValidationModePermissive
	ValidationModeStrict     = confy.ValidationModeStrict
	ValidationModeLoose      = confy.ValidationModeLoose
)
View Source
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.

View Source
const (
	HealthStatusHealthy   = shared.HealthStatusHealthy
	HealthStatusDegraded  = shared.HealthStatusDegraded
	HealthStatusUnhealthy = shared.HealthStatusUnhealthy
	HealthStatusUnknown   = shared.HealthStatusUnknown
)
View Source
const (
	LevelInfo  = logger.LevelInfo
	LevelWarn  = logger.LevelWarn
	LevelError = logger.LevelError
	LevelFatal = logger.LevelFatal
	LevelDebug = logger.LevelDebug
)

Re-export logger constants.

View Source
const (
	MetricTypeCounter   = shared.MetricTypeCounter
	MetricTypeGauge     = shared.MetricTypeGauge
	MetricTypeHistogram = shared.MetricTypeHistogram
	MetricTypeTimer     = shared.MetricTypeTimer
)

Metric type constants.

View Source
const (
	EventResumed = router.EventResumed
	EventGap     = router.EventGap
)

Reserved control event names and their payloads.

Exported so an application can name what it is told not to emit: an event under either name would convince a client that a gap was filled when it was not, and a name that cannot be referred to cannot be checked against.

View Source
const ConfigKey = "config"

ConfigKey is the service key for configuration manager Use config.ManagerKey or shared.ConfigKey for consistency.

Variables ¶

View Source
var (
	NewManager        = confy.New
	NewSourceRegistry = confy.NewSourceRegistry
	NewValidator      = confy.NewValidator
	NewWatcher        = confy.NewWatcher
	NewSecretsManager = confy.NewSecretsManager

	// NewEnvSource creates an environment variable source.
	NewEnvSource = sources.NewEnvSource

	// DiscoverAndLoadConfigs discovers and loads configuration files automatically.
	DiscoverAndLoadConfigs = confy.DiscoverAndLoadConfigs
	// DefaultAutoDiscoveryConfig returns the default auto-discovery configuration.
	DefaultAutoDiscoveryConfig = confy.DefaultAutoDiscoveryConfig
)
View Source
var (
	WithDefault   = confy.WithDefault
	WithRequired  = confy.WithRequired
	WithValidator = confy.WithValidator
	WithTransform = confy.WithTransform
	WithOnMissing = confy.WithOnMissing
	AllowEmpty    = confy.AllowEmpty
	WithCacheKey  = confy.WithCacheKey
)
View Source
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.

View Source
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().

View Source
var (
	// ErrNoScope is returned when a Scope is required but not present in the context.
	ErrNoScope = errors.Unauthorized("scope identity required")

	// ErrNoOrg is returned when an organization-level Scope is required
	// but the current Scope has no OrgID.
	ErrNoOrg = errors.Forbidden("organization scope required")
)

Scope identity errors.

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

View Source
var (
	// String creates a string field.
	String = logger.String
	// Int creates an int field.
	Int = logger.Int
	// Int8 creates an int8 field.
	Int8 = logger.Int8
	// Int16 creates an int16 field.
	Int16 = logger.Int16
	// Int32 creates an int32 field.
	Int32 = logger.Int32
	// Int64 creates an int64 field.
	Int64 = logger.Int64
	// Uint creates a uint field.
	Uint = logger.Uint
	// Uint8 creates a uint8 field.
	Uint8 = logger.Uint8
	// Uint16 creates a uint16 field.
	Uint16 = logger.Uint16
	// Uint32 creates a uint32 field.
	Uint32 = logger.Uint32
	// Uint64 creates a uint64 field.
	Uint64 = logger.Uint64
	// Float32 creates a float32 field.
	Float32 = logger.Float32
	// Float64 creates a float64 field.
	Float64 = logger.Float64
	// Bool creates a bool field.
	Bool = logger.Bool

	// Time creates a time field.
	Time = logger.Time
	// Duration creates a duration field.
	Duration = logger.Duration

	// Error creates an error field.
	Error = logger.Error

	// Stringer creates a field from a Stringer.
	Stringer = logger.Stringer
	// Any creates a field from any value.
	Any = logger.Any
	// Stack creates a stack trace field.
	Stack = logger.Stack
	// Strings creates a string slice field.
	Strings = logger.Strings

	// HTTPMethod creates an HTTP method field.
	HTTPMethod = logger.HTTPMethod
	// HTTPStatus creates an HTTP status field.
	HTTPStatus = logger.HTTPStatus
	// HTTPPath creates an HTTP path field.
	HTTPPath = logger.HTTPPath
	// HTTPURL creates an HTTP URL field.
	HTTPURL = logger.HTTPURL
	// HTTPUserAgent creates an HTTP user agent field.
	HTTPUserAgent = logger.HTTPUserAgent

	// DatabaseQuery creates a database query field.
	DatabaseQuery = logger.DatabaseQuery
	// DatabaseTable creates a database table field.
	DatabaseTable = logger.DatabaseTable
	// DatabaseRows creates a database rows affected field.
	DatabaseRows = logger.DatabaseRows

	// ServiceName creates a service name field.
	ServiceName = logger.ServiceName
	// ServiceVersion creates a service version field.
	ServiceVersion = logger.ServiceVersion
	// ServiceEnvironment creates a service environment field.
	ServiceEnvironment = logger.ServiceEnvironment

	// RequestID creates a request ID field.
	RequestID = logger.RequestID
	// TraceID creates a trace ID field.
	TraceID = logger.TraceID
	// UserID creates a user ID field.
	UserID = logger.UserID
	// ContextFields creates fields from context.
	ContextFields = logger.ContextFields

	// Custom creates a custom field.
	Custom = logger.Custom
	// Lazy creates a lazily evaluated field.
	Lazy = logger.Lazy
)

Field constructors for structured logging.

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

View Source
var (
	Track              = logger.Track
	TrackWithLogger    = logger.TrackWithLogger
	TrackWithFields    = logger.TrackWithFields
	LogPanic           = logger.LogPanic
	LogPanicWithFields = logger.LogPanicWithFields
)

Re-export utility functions.

View Source
var (
	HTTPRequestGroup   = logger.HTTPRequestGroup
	DatabaseQueryGroup = logger.DatabaseQueryGroup
	ServiceInfoGroup   = logger.ServiceInfoGroup
)

Re-export field groups.

View Source
var (
	NewHTTPError  = errors.NewHTTPError
	BadRequest    = errors.BadRequest
	Unauthorized  = errors.Unauthorized
	Forbidden     = errors.Forbidden
	NotFound      = errors.NotFound
	InternalError = errors.InternalError
)
View Source
var ErrEventIDAssignedByLog = router.ErrEventIDAssignedByLog

ErrEventIDAssignedByLog is returned by SendWithID and SendJSONWithID on a route registered WithEventLog: the log owns event IDs there. Callers that supply their own should fall back to Send/SendJSON rather than drop the event.

View Source
var (
	ErrExtensionNotRegistered = errors.New("extension not registered with app")
)

Extension-specific errors.

View Source
var NewMemoryEventLog = router.NewMemoryEventLog

NewMemoryEventLog creates a bounded in-memory event log.

View Source
var NewServiceError = errors.NewServiceError

NewServiceError creates a new service error for backward compatibility.

View Source
var WithEventLog = router.WithEventLog

WithEventLog makes an SSE route resumable on a best-effort basis. A reconnect with nothing to replay is reported as a gap, because a connection-written log cannot tell that apart from nothing having been recorded. See router.WithEventLog.

View Source
var WithProducerEventLog = router.WithProducerEventLog

WithProducerEventLog makes an SSE route resumable where the application's own producer appends to the log, so an empty replay may be reported as a completed resume. See router.WithProducerEventLog.

Functions ¶

func AppIDFrom ¶ added in v0.9.11

func AppIDFrom(ctx context.Context) string

AppIDFrom is a convenience that extracts just the AppID from context.

func GetConfy ¶ added in v0.9.0

func GetConfy(c Container) (confy.Confy, error)

GetConfy resolves the confy from the container Returns the confy instance and an error if resolution fails.

func HasType ¶ added in v0.9.0

func HasType[T any](c Container) bool

HasType checks if a service of the given type is registered.

func HasTypeNamed ¶ added in v0.9.0

func HasTypeNamed[T any](c Container, name string) bool

HasTypeNamed checks if a named service of the given type is registered.

func Inject ¶ added in v0.8.0

func Inject[T any](c Container) (T, error)

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](c),
    func(db *bun.DB) (*UserService, error) { ... },
)

func InjectGroup ¶ added in v0.9.0

func InjectGroup[T any](c Container, groupName string) ([]T, error)

InjectGroup resolves all services in a group by type. Returns a slice of all services registered with the same group name.

Usage:

forge.ProvideConstructor(c, NewHandler1, vessel.AsGroup("handlers"))
forge.ProvideConstructor(c, NewHandler2, vessel.AsGroup("handlers"))

handlers, err := forge.InjectGroup[Handler](c, "handlers")

func InjectNamed ¶ added in v0.9.0

func InjectNamed[T any](c Container, name string) (T, error)

InjectNamed resolves a named service by type. Used when you have multiple instances of the same type.

Usage:

forge.ProvideConstructor(c, NewPrimaryDB, vessel.WithName("primary"))
forge.ProvideConstructor(c, NewReplicaDB, vessel.WithName("replica"))

primary, err := forge.InjectNamed[*Database](c, "primary")
replica, err := forge.InjectNamed[*Database](c, "replica")

func InjectType ¶ added in v0.9.0

func InjectType[T any](c Container) (T, error)

InjectType resolves a service by its type. This is used with constructor injection to resolve services without string keys.

Usage:

db, err := forge.InjectType[*Database](c)
userService, err := forge.InjectType[*UserService](c)

func Must ¶

func Must[T any](c Container, name string) T

Must resolves a named service by type or panics. Only use during application startup where a panic is acceptable.

Usage:

repo := forge.Must[*UserRepository](c, "userRepo")

func MustGet ¶

func MustGet[T any](cm ConfigManager, key string) T

MustGet returns a value or panics if not found.

func MustInject ¶ added in v0.9.10

func MustInject[T any](c Container) T

MustInject resolves a dependency and panics if it fails. The dependency is resolved immediately when the service is created.

Usage:

forge.Provide(c, "userService",
    forge.MustInject[*bun.DB]("database"),
    func(db *bun.DB) (*UserService, error) { ... },
)

func MustInjectGroup ¶ added in v0.9.0

func MustInjectGroup[T any](c Container, groupName string) []T

MustInjectGroup resolves a group by type or panics.

func MustInjectNamed ¶ added in v0.9.0

func MustInjectNamed[T any](c Container, name string) T

MustInjectNamed resolves a named service by type or panics.

func OnAfterRegister ¶ added in v0.10.0

func OnAfterRegister(app App, name string, fn LifecycleHook) error

OnAfterRegister registers a hook that runs after all extensions have been registered but before they start (PhaseAfterRegister).

func OnAfterRun ¶ added in v0.10.0

func OnAfterRun(app App, name string, fn LifecycleHook) error

OnAfterRun registers a hook that runs after the HTTP server starts listening (PhaseAfterRun). Hooks at this phase run in a background goroutine and should be non-blocking.

func OnBeforeRun ¶ added in v0.10.0

func OnBeforeRun(app App, name string, fn LifecycleHook) error

OnBeforeRun registers a hook that runs after Start but before the HTTP server begins listening (PhaseBeforeRun).

This is ideal for tasks that need all extensions to be ready but should complete before the app starts accepting requests (e.g., auto-migrations).

func OnClose ¶ added in v0.10.0

func OnClose(app App, name string, fn LifecycleHook) error

OnClose registers a hook that runs before the app stops — before extensions are stopped (PhaseBeforeStop).

Use this for cleanup tasks that should run during graceful shutdown.

Example:

forge.OnClose(app, "flush-cache", func(ctx context.Context, a forge.App) error {
    return cache.Flush()
})

func OnStarted ¶ added in v0.10.0

func OnStarted(app App, name string, fn LifecycleHook) error

OnStarted registers a hook that runs after the app has fully started — after all extensions are registered and started (PhaseAfterStart).

This is a convenience wrapper around App.RegisterHookFn.

Example:

forge.OnStarted(app, "log-ready", func(ctx context.Context, a forge.App) error {
    a.Logger().Info("Application is ready!")
    return nil
})

func OrganizationIDFrom ¶ added in v0.9.11

func OrganizationIDFrom(ctx context.Context) string

OrganizationIDFrom is a convenience that extracts just the OrgID from context.

func Provide ¶ added in v0.8.0

func Provide(c Container, constructor any, opts ...ProvideOption) error

Provide registers a constructor function with automatic dependency resolution. Dependencies are inferred from function parameters and all return types (except error) are registered as services.

This follows the Uber dig pattern for constructor-based dependency injection:

  • Function parameters become dependencies (resolved by type)
  • Return types become provided services
  • Error return type is handled for construction failures

Example:

// Simple constructor
func NewUserService(db *Database, logger *Logger) *UserService {
    return &UserService{db: db, logger: logger}
}
Provide(c, NewUserService)

// Constructor with error
func NewDatabase(config *Config) (*Database, error) {
    return sql.Open(config.Driver, config.DSN)
}
Provide(c, NewDatabase)

// Using In struct for many dependencies
type ServiceParams struct {
    vessel.In
    DB     *Database
    Logger *Logger `optional:"true"`
}
func NewService(p ServiceParams) *Service {
    return &Service{db: p.DB, logger: p.Logger}
}
Provide(c, NewService)

func ProvideConstructor ¶ added in v0.9.0

func ProvideConstructor(c Container, constructor any, opts ...vessel.ConstructorOption) error

ProvideConstructor registers a service constructor with automatic type-based dependency resolution. Dependencies are resolved by their return types, making this the cleanest DI pattern.

Usage:

func NewDatabase(dsn string) *Database { return &Database{dsn: dsn} }
func NewUserService(db *Database, log forge.Logger) *UserService {
    return &UserService{db: db, log: log}
}

// Register constructors - dependencies auto-resolved by type
forge.ProvideConstructor(c, NewDatabase)
forge.ProvideConstructor(c, NewUserService)

// Resolve by type
userService, err := forge.InjectType[*UserService](c)

func ProvideValue ¶ added in v0.9.10

func ProvideValue[T any](c Container, value T, opts ...ProvideOption) error

ProvideValue registers a pre-built instance as a singleton service. The instance is registered by its type and can be resolved with Inject[T].

Example:

cfg := &Config{Port: 8080}
ProvideValue(c, cfg)

// Later:
config, _ := Inject[*Config](c)

func RegisterScoped ¶

func RegisterScoped[T any](c Container, name string, factory func(Container) (T, error)) error

RegisterScoped registers a named scoped service with the container. One instance is created per scope (e.g., per HTTP request).

Usage:

forge.RegisterScoped[*Transaction](c, "transaction",
    func(c forge.Container) (*Transaction, error) {
        db, err := forge.Inject[*sql.DB](c)
        if err != nil { return nil, err }
        tx, _ := db.Begin()
        return &Transaction{tx: tx}, nil
    },
)

func RegisterSingleton ¶

func RegisterSingleton[T any](c Container, name string, factory func(Container) (T, error)) error

RegisterSingleton registers a named singleton service with the container. The factory receives the container and returns the service instance.

Usage:

forge.RegisterSingleton(c, "userRepo", func(c forge.Container) (*UserRepo, error) {
    db, err := forge.Inject[*sql.DB](c)
    if err != nil { return nil, err }
    return NewUserRepository(db), nil
})

func RegisterSingletonWith deprecated added in v0.8.0

func RegisterSingletonWith[T any](c Container, name string, factory func(Container) (T, error)) error

RegisterSingletonWith is an alias for RegisterSingleton.

Deprecated: Use RegisterSingleton instead.

func RegisterTransient ¶

func RegisterTransient[T any](c Container, name string, factory func(Container) (T, error)) error

RegisterTransient registers a named transient service with the container. A new instance is created on every resolution.

Usage:

forge.RegisterTransient[*RequestLogger](c, "requestLogger",
    func(c forge.Container) (*RequestLogger, error) {
        return NewRequestLogger(), nil
    },
)

func RegisterValue ¶

func RegisterValue[T any](c Container, name string, value T) error

RegisterValue registers a pre-built instance as a named singleton service. The value is registered by its type under the given name.

Usage:

cfg := &AppSettings{Debug: true}
forge.RegisterValue[*AppSettings](c, "settings", cfg)

// Later:
settings, _ := forge.Resolve[*AppSettings](c, "settings")

func Resolve ¶

func Resolve[T any](c Container, name string) (T, error)

Resolve resolves a named service by type from the container. This is a convenience wrapper for InjectNamed.

Usage:

repo, err := forge.Resolve[*UserRepository](c, "userRepo")

func SafeGet ¶

func SafeGet[T any](cm ConfigManager, key string) (T, error)

SafeGet returns a value with type checking.

func SetScope ¶ added in v0.9.11

func SetScope(ctx Context, s Scope)

SetScope stores the Scope in a forge.Context. Also propagates to the underlying request context so ScopeFrom works on ctx.Context().

func WithScope ¶ added in v0.9.11

func WithScope(ctx context.Context, s Scope) context.Context

WithScope attaches a Scope to a stdlib context.Context. Use this for background jobs, gRPC handlers, or any non-HTTP path.

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)

	// Configuration queries
	MigrationsDisabled() bool

	// SetMigrationsDisabled overrides the DisableMigrations config flag at
	// runtime. CLI commands call this before app.Start() to prevent the
	// PhaseAfterRegister forward-migration hook from running when rolling back
	// or inspecting status.
	SetMigrationsDisabled(v bool)

	// CentralMigrationsEnabled reports whether the single-pass migration
	// lifecycle is enabled.
	CentralMigrationsEnabled() bool

	// CentralMigrator resolves the CentralMigrator registered in the DI
	// container (ok=true) or returns nil, false when nothing has been
	// contributed (e.g. no grove extension or CentralMigrations is off).
	CentralMigrator() (CentralMigrator, bool)
}

App represents a Forge application with lifecycle management.

func New ¶

func New(opts ...AppOption) App

New creates a new Forge application with variadic options.

func NewApp ¶

func NewApp(config AppConfig) App

NewApp creates a new Forge application.

func NewWithConfig ¶ added in v0.5.0

func NewWithConfig(config AppConfig) App

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

	// Profiling
	EnablePprof bool   // Enable pprof profiling endpoints at /_/debug/pprof (default: false)
	PprofPrefix string // URL prefix for pprof endpoints (default: "/_/debug/pprof")

	// PprofGuard authorizes access to the pprof endpoints. It is called before
	// every pprof request; return false to deny (the caller gets a 404, so the
	// endpoints are not discoverable).
	//
	// Strongly recommended whenever EnablePprof is on outside a local dev loop.
	// The endpoints expose heap and goroutine contents, allow a caller to pin a
	// CPU for an arbitrary duration, and /cmdline discloses the process argv —
	// which commonly carries credentials passed as flags.
	//
	// Nil means no authorization check.
	PprofGuard func(*http.Request) bool

	ErrorHandler ErrorHandler

	// Server
	HTTPAddress string        // Default: ":8080"
	HTTPTimeout time.Duration // Default: 30s

	// MaxRequestBodySize caps request bodies in bytes. Bodies larger than this
	// are rejected instead of being buffered, so a single request cannot drive
	// unbounded allocation. Default: 10 MiB (router.DefaultMaxRequestBodySize).
	// Negative disables the limit; override per route with WithMaxBodySize.
	MaxRequestBodySize int64

	// WebSocketOrigins is the Origin allow-list for WebSocket upgrades. Empty
	// means same-origin only — browsers send cookies with upgrades but do not
	// apply CORS to them, so an open upgrade endpoint is hijackable by any site
	// the user visits. Entries may be "https://app.example.com", "app.example.com",
	// "*.example.com", or "*" to allow any origin.
	WebSocketOrigins []string

	// Shutdown
	ShutdownTimeout time.Duration // Default: 30s
	ShutdownSignals []os.Signal   // Default: SIGINT, SIGTERM

	// Health
	HealthGracePeriod time.Duration // Grace period after startup during which health endpoints always return 200. Default: 60s

	// 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)

	// Database / Migration
	DisableMigrations bool // When true, skip auto-migrations on serve (default: false). Also settable via .forge.yaml database.disable_migrations.

	// CentralMigrations runs all MigratableExtension migrations as a single
	// ordered pass (Register-all -> migrate -> Start-all) instead of letting
	// each extension migrate independently. Default: false. Also settable via
	// .forge.yaml database.central_migrations.
	CentralMigrations bool
}

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

func WithAppDescription(description string) AppOption

WithAppDescription sets the application description.

func WithAppEnvironment ¶ added in v0.5.0

func WithAppEnvironment(environment string) AppOption

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

func WithAppLogger(logger Logger) AppOption

WithAppLogger sets the logger.

func WithAppMetrics ¶ added in v0.5.0

func WithAppMetrics(metrics Metrics) AppOption

WithAppMetrics sets the metrics provider.

func WithAppMetricsConfig ¶ added in v0.5.0

func WithAppMetricsConfig(config MetricsConfig) AppOption

WithAppMetricsConfig sets the metrics configuration.

func WithAppName ¶ added in v0.5.0

func WithAppName(name string) AppOption

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

func WithAppVersion(version string) AppOption

WithAppVersion sets the application version.

func WithCentralMigrations ¶ added in v1.7.2

func WithCentralMigrations() AppOption

WithCentralMigrations enables the single-pass, dependency-ordered migration lifecycle (Register-all -> migrate -> Start-all).

func WithConfig ¶ added in v0.5.0

func WithConfig(config AppConfig) AppOption

WithConfig replaces the entire config.

func WithConfigBaseNames ¶ added in v0.5.0

func WithConfigBaseNames(names ...string) AppOption

WithConfigBaseNames sets the config base names.

func WithConfigLocalNames ¶ added in v0.5.0

func WithConfigLocalNames(names ...string) AppOption

WithConfigLocalNames sets the config local names.

func WithConfigSearchPaths ¶ added in v0.5.0

func WithConfigSearchPaths(paths ...string) AppOption

WithConfigSearchPaths sets the config search paths.

func WithDisableMigrations ¶ added in v1.4.5

func WithDisableMigrations() AppOption

WithDisableMigrations disables auto-migrations on serve. This can also be set via .forge.yaml under database.disable_migrations.

func WithEnableAppScopedConfig ¶ added in v0.5.0

func WithEnableAppScopedConfig(enabled bool) AppOption

WithEnableAppScopedConfig enables or disables app-scoped config.

func WithEnableConfigAutoDiscovery ¶ added in v0.5.0

func WithEnableConfigAutoDiscovery(enabled bool) AppOption

WithEnableConfigAutoDiscovery enables or disables config auto-discovery.

func WithEnableEnvConfig ¶ added in v0.8.3

func WithEnableEnvConfig(enabled bool) AppOption

WithEnableEnvConfig enables or disables environment variable config source.

func WithEnvOverridesFile ¶ added in v0.8.3

func WithEnvOverridesFile(override bool) AppOption

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

func WithEnvPrefix(prefix string) AppOption

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

func WithEnvSeparator(separator string) AppOption

WithEnvSeparator sets the separator for nested keys in environment variables. Default is "_".

func WithExtensions ¶ added in v0.5.0

func WithExtensions(extensions ...Extension) AppOption

WithExtensions sets the extensions.

func WithHTTPAddress ¶ added in v0.5.0

func WithHTTPAddress(address string) AppOption

WithHTTPAddress sets the HTTP address.

func WithHTTPTimeout ¶ added in v0.5.0

func WithHTTPTimeout(timeout time.Duration) AppOption

WithHTTPTimeout sets the HTTP timeout.

func WithMaxRequestBodySize ¶ added in v1.9.0

func WithMaxRequestBodySize(bytes int64) AppOption

WithMaxRequestBodySize caps request bodies app-wide, in bytes. Defaults to 10 MiB; pass a negative value to disable the limit. Override per route with WithMaxBodySize.

func WithPprof ¶ added in v1.6.0

func WithPprof() AppOption

WithPprof enables pprof profiling endpoints. Endpoints are registered at /_/debug/pprof by default. Only enable in development or staging — never in production.

func WithPprofGuard ¶ added in v1.9.0

func WithPprofGuard(guard func(*http.Request) bool) AppOption

WithPprofGuard restricts access to the pprof endpoints. The guard runs before every pprof request; returning false yields a 404 so the endpoints stay undiscoverable. Implies WithPprof().

Use this whenever profiling is enabled on anything reachable beyond localhost: the endpoints dump heap and goroutine state, let a caller pin a CPU for an arbitrary duration, and /cmdline reveals the process argv.

forge.WithPprofGuard(func(r *http.Request) bool {
    return subtle.ConstantTimeCompare(
        []byte(r.Header.Get("X-Debug-Token")), []byte(token)) == 1
})

func WithPprofPrefix ¶ added in v1.6.0

func WithPprofPrefix(prefix string) AppOption

WithPprofPrefix sets a custom URL prefix for pprof endpoints. Implies WithPprof(). Default is "/_/debug/pprof".

func WithShutdownSignals ¶ added in v0.5.0

func WithShutdownSignals(signals ...os.Signal) AppOption

WithShutdownSignals sets the shutdown signals.

func WithShutdownTimeout ¶ added in v0.5.0

func WithShutdownTimeout(timeout time.Duration) AppOption

WithShutdownTimeout sets the shutdown timeout.

func WithWebSocketOrigins ¶ added in v1.9.0

func WithWebSocketOrigins(origins ...string) AppOption

WithWebSocketOrigins sets the Origin allow-list for WebSocket upgrades. Without it only same-origin upgrades are accepted — see AppConfig.WebSocketOrigins.

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 = confy.AutoDiscoveryConfig

Auto-Discovery Types.

type AutoDiscoveryResult ¶ added in v0.8.3

type AutoDiscoveryResult = confy.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:

  1. "extensions.{key}" - Namespaced pattern (preferred)
  2. "{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) RegisterConstructor ¶ added in v0.9.0

func (e *BaseExtension) RegisterConstructor(constructor any, opts ...vessel.ConstructorOption) error

RegisterConstructor registers a service constructor with the DI container. This is the preferred method for registering services as it uses type-based dependency injection.

The constructor function's parameters are automatically resolved by their types from the container. Config should be captured in the constructor closure when calling this method.

Example:

func (e *Extension) Register(app forge.App) error {
    e.BaseExtension.Register(app)
    cfg := e.loadConfig()

    // Register constructor - config captured in closure
    return e.RegisterConstructor(func(logger forge.Logger, metrics forge.Metrics) (*MyService, error) {
        return NewMyService(cfg, logger, metrics)
    })
}

func (*BaseExtension) RegisterConstructors ¶ added in v0.9.0

func (e *BaseExtension) RegisterConstructors(constructors ...any) error

RegisterConstructors registers multiple service constructors at once. This is a convenience method for extensions that register multiple services.

Example:

func (e *Extension) Register(app forge.App) error {
    e.BaseExtension.Register(app)
    cfg := e.loadConfig()

    return e.RegisterConstructors(
        func(logger forge.Logger) (*ServiceA, error) {
            return NewServiceA(cfg, logger)
        },
        func(logger forge.Logger, metrics forge.Metrics) (*ServiceB, error) {
            return NewServiceB(cfg, logger, metrics)
        },
    )
}

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 = confy.BindOptions

Configuration Options.

func DefaultBindOptions ¶

func DefaultBindOptions() BindOptions

DefaultBindOptions returns default bind options.

type BunRouterAdapter ¶

type BunRouterAdapter = router.BunRouterAdapter

BunRouterAdapter wraps uptrace/bunrouter.

type CLICommandProvider ¶ added in v0.10.0

type CLICommandProvider interface {
	Extension

	// CLICommands returns CLI commands contributed by this extension.
	// Each element in the returned slice must implement cli.Command.
	CLICommands() []any
}

CLICommandProvider is an optional interface for extensions that want to contribute CLI commands when the app is wrapped in a CLI runner.

The CLICommands method returns a slice of any values that must each implement cli.Command. The type is []any (rather than []cli.Command) to avoid a circular import — the forge package cannot import forge/cli since cli already imports forge.

The CLI wrapper (cli.RunApp) performs type assertions at registration time and logs warnings for values that don't implement cli.Command.

Example:

func (e *MyExtension) CLICommands() []any {
    return []any{
        cli.NewCommand("seed", "Seed the database", e.handleSeed),
        cli.NewCommand("dump", "Dump database schema", e.handleDump),
    }
}

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 CentralMigrator ¶ added in v1.7.2

type CentralMigrator interface {
	RunAll(ctx context.Context) (*MigrationResult, error)
	RollbackAll(ctx context.Context) (*MigrationResult, error)
	StatusAll(ctx context.Context) ([]*MigrationGroupInfo, error)
}

CentralMigrator runs all extension migrations as one ordered set per database. The grove MigrationRegistry implements it; it is resolved from the DI container.

type ChangeType ¶

type ChangeType = confy.ChangeType

Configuration Changes.

type Components ¶

type Components = shared.Components

Components holds reusable objects for the API spec.

type ConfigChange ¶

type ConfigChange = confy.ConfigChange

Configuration Changes.

type ConfigConfig ¶ added in v0.9.0

type ConfigConfig = confy.Config

Manager Configuration.

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 = confy.Confy

ConfigManager is the configuration manager interface.

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

NewDefaultConfigManager creates a default config manager (stub for now).

type ConfigSource ¶

type ConfigSource = confy.ConfigSource

Configuration Sources.

type ConfigSourceFactory ¶

type ConfigSourceFactory = confy.ConfigSourceFactory

Configuration Sources.

type ConfigSourceOptions ¶

type ConfigSourceOptions = confy.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 Contact ¶

type Contact = shared.Contact

Contact represents contact information.

type Container ¶

type Container = vessel.Vessel

Container provides dependency injection with lifecycle management.

func NewContainer ¶

func NewContainer() Container

NewContainer creates a new DI container.

type Context ¶

type Context = shared.Context

Context wraps http.Request with convenience methods.

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 Counter ¶

type Counter = shared.Counter

Counter tracks monotonically increasing values.

type DIScope ¶ added in v0.9.11

type DIScope = vessel.Scope

DIScope represents a lifetime scope for scoped services in the DI container. Typically used for HTTP requests or other bounded operations.

type DebugAppInfo ¶ added in v0.10.0

type DebugAppInfo struct {
	Name        string `json:"name"`
	Version     string `json:"version"`
	Environment string `json:"environment"`
	HTTPAddr    string `json:"http_addr"`
	DebugAddr   string `json:"debug_addr"`
	UptimeMs    int64  `json:"uptime_ms"`
}

DebugAppInfo contains basic application metadata.

type DebugCheckResult ¶ added in v0.10.0

type DebugCheckResult struct {
	Status     string `json:"status"`
	Message    string `json:"message,omitempty"`
	ResponseMs int64  `json:"response_ms,omitempty"`
}

DebugCheckResult is one health check's result.

type DebugExtInfo ¶ added in v0.10.0

type DebugExtInfo struct {
	Name         string   `json:"name"`
	Version      string   `json:"version"`
	Description  string   `json:"description"`
	Dependencies []string `json:"dependencies"`
	Healthy      bool     `json:"healthy"`
}

DebugExtInfo describes a registered extension.

type DebugHealth ¶ added in v0.10.0

type DebugHealth struct {
	Overall string                      `json:"overall"`
	Checks  map[string]DebugCheckResult `json:"checks"`
}

DebugHealth contains health check results.

type DebugMessage ¶ added in v0.10.0

type DebugMessage struct {
	Type      DebugMessageType `json:"type"`
	Timestamp int64            `json:"ts"`
	AppName   string           `json:"app"`
	Payload   any              `json:"payload"`
}

DebugMessage is the envelope for all WebSocket debug messages.

type DebugMessageType ¶ added in v0.10.0

type DebugMessageType string

DebugMessageType identifies the kind of debug message sent over the WebSocket.

const (
	DebugMsgSnapshot  DebugMessageType = "snapshot"  // full state on WS connect
	DebugMsgMetrics   DebugMessageType = "metrics"   // periodic metrics tick
	DebugMsgHealth    DebugMessageType = "health"    // periodic health tick
	DebugMsgLifecycle DebugMessageType = "lifecycle" // lifecycle phase event
	DebugMsgPong      DebugMessageType = "pong"
)

type DebugMetrics ¶ added in v0.10.0

type DebugMetrics struct {
	Raw string `json:"raw"`
}

DebugMetrics wraps a Prometheus text-format metrics payload.

type DebugRoute ¶ added in v0.10.0

type DebugRoute struct {
	Name        string   `json:"name,omitempty"`
	Method      string   `json:"method"`
	Path        string   `json:"path"`
	Tags        []string `json:"tags,omitempty"`
	Summary     string   `json:"summary,omitempty"`
	Description string   `json:"description,omitempty"`
}

DebugRoute describes a single registered HTTP route.

type DebugServerEntry ¶ added in v0.10.0

type DebugServerEntry struct {
	PID          int    `json:"pid"`
	AppName      string `json:"app_name"`
	AppVersion   string `json:"app_version"`
	DebugAddr    string `json:"debug_addr"`
	AppAddr      string `json:"app_addr"`
	WorkspaceDir string `json:"workspace_dir"`
	StartedAt    string `json:"started_at"`
}

DebugServerEntry is a single entry in ~/.forge/debug-servers.json.

type DebugSnapshot ¶ added in v0.10.0

type DebugSnapshot struct {
	App        DebugAppInfo   `json:"app"`
	Config     map[string]any `json:"config"`
	Services   []string       `json:"services"`
	Routes     []DebugRoute   `json:"routes"`
	Extensions []DebugExtInfo `json:"extensions"`
	Health     *DebugHealth   `json:"health,omitempty"`
}

DebugSnapshot is the full state payload sent when a WS client connects.

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

type Dep = shared.Dep

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

func DepEagerSpec(name string) Dep

DepEagerSpec creates an eager dependency specification. The dependency is resolved immediately and fails if not found.

func DepLazyOptionalSpec ¶ added in v0.8.0

func DepLazyOptionalSpec(name string) Dep

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

func DepLazySpec(name string) Dep

DepLazySpec creates a lazy dependency specification. The dependency is resolved on first access.

func DepOptionalSpec ¶ added in v0.8.0

func DepOptionalSpec(name string) Dep

DepOptionalSpec creates an optional dependency specification. The dependency is resolved immediately but returns nil if not found.

type DepMode ¶ added in v0.8.0

type DepMode = shared.DepMode

DepMode specifies how a dependency should be resolved.

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 EmitsBuilder ¶ added in v1.9.3

type EmitsBuilder = router.EmitsBuilder

EmitsBuilder accumulates one stream binding.

func Emits ¶ added in v1.9.3

func Emits[T any](message string) *EmitsBuilder

Emits declares that a channel emits `message` carrying entity T.

Example:

router.WebSocket("/ws/orders", handler,
    forge.WithStreamBinding(
        forge.Emits[Order]("order.created"),
        forge.Emits[Order]("order.updated"),
        forge.Emits[Order]("order.deleted"),
    ),
)

type Encoding ¶

type Encoding = shared.Encoding

Encoding defines encoding for a property.

type EntityDef ¶ added in v1.9.3

type EntityDef = router.EntityDef

EntityDef declares how a type is identified in a client-side normalized cache.

IDField is the JSON property name in the response body -- `id`, `order_number` -- not the Go field name.

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 EnvelopeDef ¶ added in v1.9.3

type EnvelopeDef = router.EnvelopeDef

EnvelopeDef declares which JSON property of a wrapper type carries the entity. Leave ItemsField empty to have generation resolve the sole entity-typed property.

type ErrorHandler ¶

type ErrorHandler = shared.ErrorHandler

ErrorHandler handles errors from handlers.

func NewDefaultErrorHandler ¶

func NewDefaultErrorHandler(l Logger) ErrorHandler

NewDefaultErrorHandler creates a default error handler.

type EventLog ¶ added in v1.9.5

type EventLog = router.EventLog

EventLog stores recent events so a reconnecting SSE client can be handed the ones it missed. See WithEventLog.

type Example ¶

type Example = shared.Example

Example provides an example value.

type Extension ¶

type Extension interface {
	// Name returns the unique name of the extension
	Name() string

	// Version returns the semantic version of the extension
	Version() string

	// Description returns a human-readable description
	Description() string

	// 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:

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

type 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:

  1. Try loading from "extensions.{name}" key
  2. Fallback to "{name}" key (legacy/v1 compatibility)
  3. Use provided defaults if config not found
  4. 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:

  1. "extensions.{key}" - Namespaced pattern (preferred)
  2. "{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.

func (*ExternalAppExtension) Run ¶ added in v0.4.0

Run starts the external application.

func (*ExternalAppExtension) Shutdown ¶ added in v0.4.0

func (e *ExternalAppExtension) Shutdown(ctx context.Context) error

Shutdown gracefully stops the external application.

type ExternalDocs ¶

type ExternalDocs = shared.ExternalDocs

ExternalDocs points to external documentation.

type ExternalDocsDef ¶

type ExternalDocsDef = router.ExternalDocsDef

ExternalDocsDef defines external documentation.

type Factory ¶

type Factory = vessel.Factory

Factory creates a service instance.

type Field ¶

type Field = logger.Field

Re-export logger interfaces for 100% v1 compatibility.

func F ¶

func F(key string, value any) Field

F creates a new field (alias for Any for backwards compatibility with Phase 7).

type ForgeEntity ¶ added in v1.9.3

type ForgeEntity = router.ForgeEntity

ForgeEntity is implemented by types that override entity inference. The schema generator honours it, marking the declared id property so identity travels with the type rather than being repeated on every route.

The marker beats the `id` name heuristic, so this is the way to say "the field named id is not what identifies this record". Declare identity once per type: this and the `forge:"id"` struct tag write the same marker, and using both on different fields resolves to no entity at all.

Example:

type Order struct {
    Number string `json:"order_number"`
    Total  int    `json:"total"`
}

func (Order) ForgeEntity() forge.EntityDef {
    return forge.EntityDef{Type: "Order", IDField: "order_number"}
}

type ForgeEnvelope ¶ added in v1.9.3

type ForgeEnvelope = router.ForgeEnvelope

ForgeEnvelope is implemented by types that WRAP an entity rather than being one -- a paginated page, a `{data, meta}` result.

It is what makes a paginated list cacheable. An endpoint returning `PageOrder{Items []Order; Total int}` returns a document in which nothing is an entity, so without this it gets no identity and no invalidation tags. Declaring the wrapper a wrapper gives the operation exactly the contract returning `[]Order` would.

The orders inside such a response are normalized either way -- the generated field map routes into them without any declaration. This adds the cache contract, which is the part that cannot be inferred: `PageOrder` and an `OrderReport{TopOrders []Order}` are the same shape, and only one of them is the collection.

Example:

type PageOrder struct {
    Items []Order `json:"items"`
    Total int     `json:"total"`
}

func (PageOrder) ForgeEnvelope() forge.EnvelopeDef { return forge.EnvelopeDef{} }

type GapPayload ¶ added in v1.9.5

type GapPayload = router.GapPayload

GapPayload tells the client the gap could not be filled.

type Gauge ¶

type Gauge = shared.Gauge

Gauge tracks values that can go up or down.

type GetOption ¶

type GetOption = confy.GetOption

Configuration Options.

type GetOptions ¶

type GetOptions = confy.GetOptions

Configuration Options.

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

WithGroupMiddleware adds middleware to a route group.

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 HTTPError ¶

type HTTPError = errors.HTTPError

HTTPError represents an HTTP error for backward compatibility.

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 Handler ¶ added in v0.5.0

type Handler = router.Handler

Handler is a forge handler function.

type HandlerPattern ¶

type HandlerPattern int

HandlerPattern indicates the handler signature.

const (
	PatternStandard    HandlerPattern = iota // func(w, r)
	PatternContext                           // func(ctx) error
	PatternOpinionated                       // func(ctx, req) (resp, error)
	PatternService                           // func(ctx, svc) error
	PatternCombined                          // func(ctx, svc, req) (resp, error)
)
type Header = shared.Header

Header describes a single header parameter.

type 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 HealthFeatures ¶ added in v0.9.0

type HealthFeatures = shared.HealthFeatures

HealthFeatures configures health features.

type HealthIntervals ¶ added in v0.9.0

type HealthIntervals = shared.HealthIntervals

HealthIntervals configures health intervals.

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 HealthPerformance ¶ added in v0.9.0

type HealthPerformance = shared.HealthPerformance

HealthPerformance configures health performance.

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 Histogram ¶

type Histogram = shared.Histogram

Histogram tracks distributions of values.

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 Info ¶

type Info = shared.Info

Info provides metadata about the API.

type InternalExtension ¶ added in v0.7.0

type InternalExtension = router.InternalExtension

InternalExtension is re-exported from router package for convenience.

type LazyRef ¶ added in v0.8.0

type LazyRef[T any] = vessel.Lazy[T]

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.

func NewLazyRef ¶ added in v0.8.0

func NewLazyRef[T any](c Container, name string) *LazyRef[T]

NewLazyRef creates a new lazy dependency wrapper.

type License ¶

type License = shared.License

License represents license information.

type LifecycleHook ¶ added in v0.4.0

type LifecycleHook func(ctx context.Context, app App) error

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

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

type LogLevel ¶

type LogLevel = logger.LogLevel

Re-export logger interfaces for 100% v1 compatibility.

type LoggedEvent ¶ added in v1.9.5

type LoggedEvent = router.LoggedEvent

LoggedEvent is one recorded event, as it will be replayed.

type Logger ¶

type Logger = logger.Logger

Re-export logger interfaces for 100% v1 compatibility.

func GetLogger ¶ added in v0.5.0

func GetLogger(c Container) (Logger, error)

GetLogger resolves the logger from the container Returns the logger instance and an error if resolution fails.

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

type Map = map[string]any

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 MediaType ¶

type MediaType = shared.MediaType

MediaType provides schema and examples for a media type.

type MemoryEventLog ¶ added in v1.9.5

type MemoryEventLog = router.MemoryEventLog

MemoryEventLog is the bounded in-memory log NewMemoryEventLog returns. Aliased so applications can name it in a struct field or signature — the constructor alone leaves the type unwriteable outside this package.

type MemoryEventLogOptions ¶ added in v1.9.5

type MemoryEventLogOptions = router.MemoryEventLogOptions

MemoryEventLogOptions configures NewMemoryEventLog.

type MetricOption ¶ added in v0.9.0

type MetricOption = shared.MetricOption

MetricOption configures individual metric options.

func WithLabel ¶ added in v0.9.7

func WithLabel(key, value string) MetricOption

WithLabel creates a MetricOption that adds a label key-value pair to a metric.

func WithLabels ¶ added in v0.9.7

func WithLabels(labels map[string]string) MetricOption

WithLabels creates a MetricOption that adds multiple labels to a metric.

type MetricType ¶

type MetricType = shared.MetricType

MetricType represents the type of metric.

type Metrics ¶

type Metrics = shared.Metrics

Metrics provides telemetry collection.

func GetMetrics ¶ added in v0.5.0

func GetMetrics(c Container) (Metrics, error)

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 MetricsCollection ¶ added in v0.9.0

type MetricsCollection = shared.MetricsCollection

MetricsCollection configures metrics collection.

type MetricsConfig ¶

type MetricsConfig = shared.MetricsConfig

MetricsConfig configures metrics collection.

func DefaultMetricsConfig ¶

func DefaultMetricsConfig() MetricsConfig

DefaultMetricsConfig returns default metrics configuration.

type MetricsFeatures ¶ added in v0.9.0

type MetricsFeatures = shared.MetricsFeatures

MetricsFeatures configures metrics features.

type MetricsLimits ¶ added in v0.9.0

type MetricsLimits = shared.MetricsLimits

MetricsLimits configures metrics limits.

type Middleware ¶

type Middleware = router.Middleware

Middleware wraps HTTP handlers.

func RequireOrg ¶ added in v0.9.11

func RequireOrg() Middleware

RequireOrg is middleware that ensures the Scope includes an organization. Returns ErrNoScope (HTTP 401) if no scope is present, or ErrNoOrg (HTTP 403) if the scope lacks an OrgID.

func RequireScope ¶ added in v0.9.11

func RequireScope() Middleware

RequireScope is middleware that ensures a Scope is present in the context. Returns ErrNoScope (HTTP 401) if missing.

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 MigratableExtension ¶ added in v0.10.0

type MigratableExtension interface {
	Extension

	// Migrate runs all pending migrations forward.
	// Returns the result describing which migrations were applied.
	Migrate(ctx context.Context) (*MigrationResult, error)

	// Rollback rolls back the last batch of applied migrations.
	// Returns the result describing which migrations were rolled back.
	Rollback(ctx context.Context) (*MigrationResult, error)

	// MigrationStatus returns the current state of all migrations
	// grouped by their owning module/extension.
	MigrationStatus(ctx context.Context) ([]*MigrationGroupInfo, error)
}

MigratableExtension is an optional interface for extensions that provide database migrations. Extensions implementing this interface will have their migrations auto-discovered by the CLI wrapper and can be run via lifecycle hooks or CLI commands.

The interface is database-agnostic — implementations wrap their concrete migration systems (grove/migrate, goose, golang-migrate, etc.).

Migrations are discovered from all registered extensions that implement this interface. The CLI wrapper provides `migrate up`, `migrate down`, and `migrate status` commands automatically.

Example implementation:

func (e *MyDBExtension) Migrate(ctx context.Context) (*forge.MigrationResult, error) {
    result, err := e.orchestrator.Migrate(ctx)
    if err != nil {
        return nil, err
    }
    return &forge.MigrationResult{Applied: len(result.Applied)}, nil
}

func (e *MyDBExtension) Rollback(ctx context.Context) (*forge.MigrationResult, error) {
    result, err := e.orchestrator.Rollback(ctx)
    if err != nil {
        return nil, err
    }
    return &forge.MigrationResult{RolledBack: len(result.Rollback)}, nil
}

func (e *MyDBExtension) MigrationStatus(ctx context.Context) ([]*forge.MigrationGroupInfo, error) {
    // ... convert internal status to forge types ...
}

type MigrationGroupInfo ¶ added in v0.10.0

type MigrationGroupInfo struct {
	// Name is the group identifier (e.g., "core", "billing").
	Name string

	// Applied lists migrations that have already been applied.
	Applied []*MigrationInfo

	// Pending lists migrations that have not yet been applied.
	Pending []*MigrationInfo
}

MigrationGroupInfo describes the status of all migrations in a group.

type MigrationInfo ¶ added in v0.10.0

type MigrationInfo struct {
	// Name is a human-readable identifier (e.g., "create_users").
	Name string

	// Version is a timestamp-based version string (e.g., "20240115120000").
	Version string

	// Group identifies the module/extension that owns this migration.
	Group string

	// Comment is an optional description of what this migration does.
	Comment string

	// Applied indicates whether this migration has been applied.
	Applied bool

	// AppliedAt is an ISO 8601 timestamp of when the migration was applied.
	// Empty if not yet applied.
	AppliedAt string
}

MigrationInfo describes a single migration for display and status purposes. It is database-agnostic — extensions convert their internal migration types to this format for CLI display and programmatic inspection.

type MigrationResult ¶ added in v0.10.0

type MigrationResult struct {
	// Applied is the count of newly applied migrations (for Migrate).
	Applied int

	// RolledBack is the count of rolled-back migrations (for Rollback).
	RolledBack int

	// Names lists the affected migration identifiers (group/name format).
	Names []string
}

MigrationResult describes the outcome of a Migrate or Rollback operation.

type OAuthFlow ¶

type OAuthFlow = shared.OAuthFlow

OAuthFlow defines a single OAuth 2.0 flow.

type OAuthFlows ¶

type OAuthFlows = shared.OAuthFlows

OAuthFlows defines OAuth 2.0 flows.

type 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 Operation ¶

type Operation = shared.Operation

Operation describes a single API operation on a path.

type OptionalLazyRef ¶ added in v0.8.0

type OptionalLazyRef[T any] = vessel.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 Parameter ¶

type Parameter = shared.Parameter

Parameter describes a single operation parameter.

type ParameterDef ¶

type ParameterDef = router.ParameterDef

ParameterDef defines a parameter.

type PathItem ¶

type PathItem = shared.PathItem

PathItem describes operations available on a single path.

type ProvideOption ¶ added in v0.9.10

type ProvideOption = vessel.ConstructorOption

ProvideOption is an alias for vessel.ConstructorOption, used to configure options for constructing objects.

type ProviderRef ¶ added in v0.8.0

type ProviderRef[T any] = vessel.Provider[T]

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

FromMiddleware 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 Response ¶

type Response = shared.Response

Response describes a single response from an API operation.

type ResponseDef ¶

type ResponseDef = router.ResponseDef

ResponseDef defines a response.

type ResponseSchemaDef ¶

type ResponseSchemaDef = router.ResponseSchemaDef

ResponseSchemaDef defines a response schema.

type ResumedPayload ¶ added in v1.9.5

type ResumedPayload = router.ResumedPayload

ResumedPayload closes a replay: the position resumed from and how many events were delivered.

type RouteConfig ¶

type RouteConfig = router.RouteConfig

RouteConfig holds route configuration.

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 RouteInfo ¶

type RouteInfo = router.RouteInfo

RouteInfo provides route information for inspection.

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 WithEntity ¶ added in v1.9.3

func WithEntity(def EntityDef) RouteOption

WithEntity overrides inferred identity for this endpoint's response.

IDField is the JSON property name, so it must match the key that appears in the response body -- `id`, not the Go field name `ID`. Generation warns when the named property is absent from the response schema, because as declared it would produce a cache key that never matches a record.

Prefer implementing ForgeEntity on the type: identity is intrinsic to a type, and declaring it per route repeats it on every endpoint returning an Order. This option exists for types you cannot add a method to, and for the one endpoint whose response is identified differently from the rest.

Example:

router.GET("/orders/{id}", getOrder,
    forge.WithEntity(forge.EntityDef{Type: "Order", IDField: "id"}),
)

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 WithInvalidates ¶ added in v1.9.3

func WithInvalidates(tags ...string) RouteOption

WithInvalidates declares cross-entity invalidation effects. Same-entity invalidation is derived, so this is only for edges a reader would not predict.

Example:

router.POST("/orders", createOrder,
    forge.WithInvalidates("Inventory[]", "Customer:{req.customerId}"),
)

func WithListResponse ¶

func WithListResponse(itemType any, statusCode int) RouteOption

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

func WithMaxBodySize ¶ added in v1.9.0

func WithMaxBodySize(bytes int64) RouteOption

WithMaxBodySize caps this route's request body in bytes, overriding the app-wide MaxRequestBodySize. Raise it for upload endpoints; pass a negative value for no limit on this route.

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 WithName ¶

func WithName(name string) RouteOption

WithName sets the route name.

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 WithStreamBinding ¶ added in v1.9.3

func WithStreamBinding(builders ...*EmitsBuilder) RouteOption

WithStreamBinding declares which entity updates a channel emits.

Example:

router.WebSocket("/ws/orders", handler,
    forge.WithStreamBinding(
        forge.Emits[Order]("order.created"),
        forge.Emits[Order]("order.updated"),
        forge.Emits[Order]("order.deleted"),
    ),
)

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.

func WithoutEntity ¶ added in v1.9.3

func WithoutEntity() RouteOption

WithoutEntity keeps this endpoint's response out of the normalized store. Use it for projections and snapshots that must not merge with the canonical record.

Example:

router.GET("/orders/{id}/audit-snapshot", h, forge.WithoutEntity())

func WithoutInvalidation ¶ added in v1.9.3

func WithoutInvalidation(tags ...string) RouteOption

WithoutInvalidation suppresses a derived invalidation for endpoints that cannot change list membership.

type Router ¶

type Router = router.Router

Router provides HTTP routing with multiple backend support.

func GetRouter ¶ added in v0.5.0

func GetRouter(c Container) (Router, error)

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

WithAdapter sets the router adapter.

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 SSEHandler ¶

type SSEHandler = router.SSEHandler

SSEHandler handles Server-Sent Events.

type Schema ¶

type Schema = shared.Schema

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

type Scope ¶

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

Scope identifies the current execution context — who is making this request. It carries both App and Org identity. Org may be empty for app-level operations.

Scope is intentionally a value type (not a pointer) so it's safe to copy, compare, and use as a map key.

func GetScope ¶ added in v0.9.11

func GetScope(ctx Context) (Scope, bool)

GetScope retrieves the Scope from a forge.Context. Checks the forge context map first, then falls back to the stdlib request context.

func MustGetScope ¶ added in v0.9.11

func MustGetScope(ctx Context) Scope

MustGetScope retrieves the Scope from forge.Context or panics.

func MustScope ¶

func MustScope(ctx context.Context) Scope

MustScope extracts the Scope or panics. Use after auth middleware.

func NewAppScope ¶ added in v0.9.11

func NewAppScope(appID string) Scope

NewAppScope creates a scope for app-level operations (no org).

func NewOrgScope ¶ added in v0.9.11

func NewOrgScope(appID, orgID string) Scope

NewOrgScope creates a scope for org-level operations.

func ScopeFrom ¶ added in v0.9.11

func ScopeFrom(ctx context.Context) (Scope, bool)

ScopeFrom extracts the Scope from a stdlib context.Context. Returns the scope and true if found, zero Scope and false otherwise.

func (Scope) AppID ¶ added in v0.9.11

func (s Scope) AppID() string

AppID returns the app identifier. Always present.

func (Scope) HasOrg ¶ added in v0.9.11

func (s Scope) HasOrg() bool

HasOrg returns true if this scope includes an organization.

func (Scope) IsZero ¶ added in v0.9.11

func (s Scope) IsZero() bool

IsZero returns true if the scope is unset.

func (Scope) Key ¶ added in v0.9.11

func (s Scope) Key(level ScopeLevel) string

Key returns the scoping key for the given level. Extensions use this to decide what to scope by.

scope.Key(ScopeApp) → "app_01h9a1b2c3"  (always works)
scope.Key(ScopeOrganization) → "org_01h9a1b2c4"  (panics if no org)

func (Scope) Level ¶ added in v0.9.11

func (s Scope) Level() ScopeLevel

Level returns whether this scope is app-level or org-level.

func (Scope) OrgID ¶ added in v0.9.11

func (s Scope) OrgID() string

OrgID returns the org identifier. Empty for app-level scopes.

func (Scope) String ¶ added in v0.9.11

func (s Scope) String() string

String returns a human-readable representation. "app_01h9a1b2c3" or "app_01h9a1b2c3/org_01h9a1b2c4".

type ScopeLevel ¶ added in v0.9.11

type ScopeLevel int

ScopeLevel indicates the isolation level.

const (
	// ScopeApp indicates app-level operations: platform config, plans, global policies.
	ScopeApp ScopeLevel = iota
	// ScopeOrganization indicates org-level operations: customer data, usage, isolation.
	ScopeOrganization
)

func (ScopeLevel) String ¶ added in v0.9.11

func (l ScopeLevel) String() string

String returns a human-readable representation of the scope level.

type SecretProvider ¶

type SecretProvider = confy.SecretProvider

Secrets.

type SecretsConfig ¶

type SecretsConfig = confy.SecretsConfig

Secrets.

type SecretsManager ¶

type SecretsManager = confy.SecretsManager

Secrets.

type SecurityRequirement ¶

type SecurityRequirement = shared.SecurityRequirement

SecurityRequirement lists required security schemes.

type SecurityScheme ¶

type SecurityScheme = shared.SecurityScheme

SecurityScheme defines a security scheme.

type Service ¶

type Service = shared.Service

Service is the standard interface for managed services Container auto-detects and calls these methods.

type ServiceError ¶

type ServiceError = errors.ServiceError

ServiceError represents a service-level error for backward compatibility.

type ServiceInfo ¶

type ServiceInfo = vessel.ServiceInfo

ServiceInfo contains diagnostic information.

type SourceConfig ¶

type SourceConfig = confy.SourceConfig

Configuration Sources.

type SourceEvent ¶

type SourceEvent = confy.SourceEvent

Configuration Sources.

type SourceEventHandler ¶

type SourceEventHandler = confy.SourceEventHandler

Configuration Sources.

type SourceMetadata ¶

type SourceMetadata = confy.SourceMetadata

Configuration Sources.

type SourceRegistry ¶

type SourceRegistry = confy.SourceRegistry

Configuration Sources.

type Stream ¶

type Stream = router.Stream

Stream represents a Server-Sent Events stream.

type StreamBinding ¶ added in v1.9.3

type StreamBinding = router.StreamBinding

StreamBinding binds one channel message to an entity type.

type StreamConfig ¶

type StreamConfig = router.StreamConfig

StreamConfig configures streaming behavior.

func DefaultStreamConfig ¶

func DefaultStreamConfig() StreamConfig

DefaultStreamConfig returns default streaming configuration.

type StreamIntent ¶ added in v1.9.3

type StreamIntent = router.StreamIntent

StreamIntent is what a stream message does to the cache.

type StringMap ¶ added in v0.3.0

type StringMap = map[string]string

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 ValidationConfig ¶

type ValidationConfig = confy.ValidationConfig

Validation.

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 ValidationMode ¶

type ValidationMode = confy.ValidationMode

Validation.

type ValidationOptions ¶

type ValidationOptions = confy.ValidationOptions

Validation.

type ValidationRule ¶

type ValidationRule = confy.ValidationRule

Validation.

type Validator ¶

type Validator = confy.Validator

Validation.

type WatchContext ¶

type WatchContext = confy.WatchContext

Configuration Sources.

type Watcher ¶

type Watcher = confy.Watcher

Watcher.

type WatcherConfig ¶

type WatcherConfig = confy.WatcherConfig

Watcher.

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.

Directories ¶

Path Synopsis
cli
examples/plugin command
examples/simple command
cmd
dashboard-contract-probe command
main.go
main.go
forge module
examples
lifecycle-hooks command
observability command
sse-streaming command
extensions
dashboard/auth
Package dashauth provides authentication and authorization abstractions for the dashboard extension.
Package dashauth provides authentication and authorization abstractions for the dashboard extension.
dashboard/contract
Package contract defines the declarative, single-endpoint contract for the admin dashboard: contributor manifests, request/response envelopes, the permission model, the slot/graph composition rules, and the per-contributor version negotiation protocol.
Package contract defines the declarative, single-endpoint contract for the admin dashboard: contributor manifests, request/response envelopes, the permission model, the slot/graph composition rules, and the per-contributor version negotiation protocol.
dashboard/contract/components
Package components provides typed, fluent builders for authoring dashboard contract graphs from Go.
Package components provides typed, fluent builders for authoring dashboard contract graphs from Go.
dashboard/contract/dispatcher
Package dispatcher implements transport.Dispatcher and transport.SubscriptionSource against a function-table of registered handlers.
Package dispatcher implements transport.Dispatcher and transport.SubscriptionSource against a function-table of registered handlers.
dashboard/contract/idempotency
Package idempotency provides command deduplication for the dashboard contract: a Store interface plus an in-memory implementation.
Package idempotency provides command deduplication for the dashboard contract: a Store interface plus an in-memory implementation.
validate.go
dashboard/contract/pilot
Package pilot ships the migrated dashboard contributor used to validate the contract end-to-end: extensions.list, services.list, services.detail, and the metrics.summary subscription, all wired against the existing collector and contributor registry.
Package pilot ships the migrated dashboard contributor used to validate the contract end-to-end: extensions.list, services.list, services.detail, and the metrics.summary subscription, all wired against the existing collector and contributor registry.
dashboard/contract/remote
Package remote implements the contract dispatcher's HTTP forwarding layer.
Package remote implements the contract dispatcher's HTTP forwarding layer.
dashboard/contract/server
Package server exposes the two HTTP endpoints a non-dashboard service needs to advertise itself as a contract contributor that other dashboards can discover + dispatch into.
Package server exposes the two HTTP endpoints a non-dashboard service needs to advertise itself as a contract contributor that other dashboards can discover + dispatch into.
capabilities.go
dashboard/contributor/codegen
Package codegen generates Go source files from forge.contributor.yaml configuration.
Package codegen generates Go source files from forge.contributor.yaml configuration.
dashboard/contributor/config
Package config defines the schema for forge.contributor.yaml configuration files that declare dashboard contributor metadata, navigation, widgets, settings, and build configuration.
Package config defines the schema for forge.contributor.yaml configuration files that declare dashboard contributor metadata, navigation, widgets, settings, and build configuration.
dashboard/examples/basic command
Package main demonstrates a basic dashboard setup with built-in pages only.
Package main demonstrates a basic dashboard setup with built-in pages only.
dashboard/examples/contributor command
Package main demonstrates how to create a custom LocalContributor that adds pages, widgets, and settings to the dashboard.
Package main demonstrates how to create a custom LocalContributor that adds pages, widgets, and settings to the dashboard.
dashboard/examples/remote command
Package main demonstrates how to register a remote contributor with the dashboard extension.
Package main demonstrates how to register a remote contributor with the dashboard extension.
dashboard/layouts
templ: version: v0.3.1001
templ: version: v0.3.1001
dashboard/theme
Package theme provides a dashboard-specific wrapper around the forgeui theme system.
Package theme provides a dashboard-specific wrapper around the forgeui theme system.
dashboard/ui
templ: version: v0.3.1001
templ: version: v0.3.1001
dashboard/ui/pages
templ: version: v0.3.1001
templ: version: v0.3.1001
dashboard/ui/shell
templ: version: v0.3.1001
templ: version: v0.3.1001
ai module
cache module
consensus module
cron module
database module
discovery module
events module
features module
gateway module
graphql module
grpc module
kafka module
mcp module
mqtt module
orpc module
queue module
search module
security module
storage module
streaming module
webrtc module
Package farp provides Forge-specific integrations for the FARP protocol.
Package farp provides Forge-specific integrations for the FARP protocol.
examples/basic command
Package interceptors provides pre-built interceptors for forge routes.
Package interceptors provides pre-built interceptors for forge routes.
internal
router/testtypes/billing
Package billing provides test fixture types whose names deliberately collide with types in sibling fixture packages, so OpenAPI component-name collision handling can be exercised from the router tests.
Package billing provides test fixture types whose names deliberately collide with types in sibling fixture packages, so OpenAPI component-name collision handling can be exercised from the router tests.
router/testtypes/shipping
Package shipping provides test fixture types whose names deliberately collide with types in sibling fixture packages, so OpenAPI component-name collision handling can be exercised from the router tests.
Package shipping provides test fixture types whose names deliberately collide with types in sibling fixture packages, so OpenAPI component-name collision handling can be exercised from the router tests.
router/testtypes/warehouse
Package warehouse provides test fixture types whose names deliberately collide with types in sibling fixture packages, so OpenAPI component-name collision handling can be exercised from the router tests.
Package warehouse provides test fixture types whose names deliberately collide with types in sibling fixture packages, so OpenAPI component-name collision handling can be exercised from the router tests.

Jump to

Keyboard shortcuts

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