forge

package module
v0.8.6 Latest Latest
Warning

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

Go to latest
Published: Jan 3, 2026 License: Apache-2.0 Imports: 22 Imported by: 0

README ΒΆ

πŸ”¨ Forge

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

Enterprise-Grade Web Framework for Go

Build scalable, maintainable, and observable Go applications with Forgeβ€”the modern framework that brings clean architecture, dependency injection, and powerful extensions to your production services.

Go Version License GitHub Stars CI/CD


πŸš€ Quick Start

Installation
# Install the Forge CLI
go install github.com/xraph/forge/cmd/forge@latest

# Verify installation
forge --version
Forge Your First App
# Initialize a new project
forge init my-app

# Start the development server
forge dev
Minimal Example
package main

import "github.com/xraph/forge"

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

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

    // Run the application (blocks until SIGINT/SIGTERM)
    app.Run()
}

Built-in endpoints:

  • /_/info - Application information
  • /_/metrics - Prometheus metrics
  • /_/health - Health checks

✨ Key Features

πŸ—οΈ Core Framework
  • βœ… Dependency Injection - Type-safe container with service lifecycle
  • βœ… HTTP Router - Fast, lightweight routing with middleware support
  • βœ… Middleware - Auth, CORS, logging, rate limiting, and more
  • βœ… Configuration - YAML/JSON/TOML support with environment variable override
  • βœ… Observability - Structured logging, metrics, distributed tracing
  • βœ… Health Checks - Automatic discovery and reporting
  • βœ… Lifecycle Management - Graceful startup and shutdown
πŸ”Œ Extensions
Extension Description Status
AI LLM integration, agents, inference engine βœ…
Auth Multi-provider authentication (OAuth, JWT, SAML) βœ…
Cache Multi-backend caching (Redis, Memcached, In-Memory) βœ…
Consensus Raft consensus for distributed systems βœ…
Database SQL (Postgres, MySQL, SQLite) + MongoDB support βœ…
Events Event bus and event sourcing βœ…
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 βœ…
orpc ORPC transport protocol βœ…
Queue Message queue management βœ…
Search Full-text search (Elasticsearch, Typesense) βœ…
Storage Multi-backend storage (S3, GCS, Local) βœ…
Streaming WebSocket, SSE, WebRTC βœ…
WebRTC Real-time peer-to-peer communication βœ…
πŸ› οΈ CLI Tools
  • βœ… Project Scaffolding - Initialize new projects with templates
  • βœ… Code Generation - Generate handlers, controllers, and services
  • βœ… Database Migrations - Schema management with versioning
  • βœ… Interactive Prompts - Arrow-key navigation, multi-select
  • βœ… Server Management - Development server with hot reload
  • βœ… Testing - Built-in test runner and coverage reports

πŸ“– Documentation

Getting Started
Core Concepts
Extensions
CLI Reference

🌟 Why Forge?

Production-Ready

Forge is built for production from day one:

  • βœ… Graceful Shutdown - Proper resource cleanup on SIGTERM
  • βœ… Health Monitoring - Automatic discovery and reporting
  • βœ… Observability - Metrics, logging, and distributed tracing
  • βœ… Error Handling - Comprehensive error management
  • βœ… Security - Built-in security best practices
Developer Experience
  • βœ… Type Safety - Generics and compile-time guarantees
  • βœ… Zero Config - Sensible defaults with full customization
  • βœ… Hot Reload - Instant feedback during development
  • βœ… CLI Tools - Fast project scaffolding and generation
  • βœ… Rich Docs - Comprehensive documentation and examples
Performance
  • βœ… Low Latency - Optimized HTTP router and middleware
  • βœ… Efficient Routing - Trie-based path matching
  • βœ… Concurrent Safe - Thread-safe components
  • βœ… Memory Efficient - Minimal allocations
Extensible
  • βœ… Extension System - Modular, composable extensions
  • βœ… Plugin Architecture - Easy to add custom functionality
  • βœ… Multi-Backend - Switch implementations without code changes
  • βœ… Middleware Chain - Powerful middleware composition

πŸ›οΈ Architecture

// Application Structure
app := forge.NewApp(forge.AppConfig{
    Name:        "my-service",
    Version:     "1.0.0",
    Environment: "production",
    
    // Extensions
    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",
            // ... auth configuration
        }),
    },
})

// Dependency Injection
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
})

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

// Run
app.Run()

🧩 Extension Example

Using the AI Extension
package main

import (
    "github.com/xraph/forge"
    "github.com/xraph/forge/extensions/ai"
)

func main() {
    app := forge.NewApp(forge.AppConfig{
        Extensions: []forge.Extension{
            ai.NewExtension(ai.Config{
                LLMProviders: map[string]ai.LLMProviderConfig{
                    "openai": {
                        APIKey: os.Getenv("OPENAI_API_KEY"),
                        Model:  "gpt-4",
                    },
                },
            }),
        },
    })

    // Access AI service via DI using helper function
    aiService, err := ai.GetAIService(app.Container())
    if err != nil {
        log.Fatal(err)
    }

    // Use in your handlers
    router := app.Router()
    router.POST("/chat", func(ctx forge.Context) error {
        result, err := aiService.Chat(ctx, ai.ChatRequest{
            Messages: []ai.Message{
                {Role: "user", Content: "Hello!"},
            },
        })
        if err != nil {
            return err
        }
        return ctx.JSON(200, result)
    })

    app.Run()
}

πŸ› οΈ Development

Prerequisites
  • Go 1.24+ - Latest Go compiler
  • Make - Build tool (optional but recommended)
Build
# Build the CLI
make build

# Build with debug symbols
make build-debug

# Build for all platforms
make release
Run Tests
# Run all tests
make test

# Run with coverage
make test-coverage

# Run specific package
go test ./extensions/ai/...
Code Quality
# Format code
make fmt

# Run linter
make lint

# Fix linting issues
make lint-fix

# Run security scan
make security-scan

# Check vulnerabilities
make vuln-check
Development Server
# Start development server
forge dev

# Start with hot reload
forge dev --watch

# Start on custom port
forge dev --port 3000

πŸ“Š Project Status

Core Framework
  • βœ… Dependency Injection - Production ready
  • βœ… HTTP Router - Fast, lightweight
  • βœ… Middleware System - Comprehensive
  • βœ… Configuration - Multi-format support
  • βœ… Observability - Metrics, logging, tracing
  • βœ… Health Checks - Automatic discovery
  • βœ… CLI Tools - Full-featured CLI
Extensions (17 total)

Production Ready (14):

  • βœ… AI - LLM integration and agents
  • βœ… Auth - Multi-provider authentication
  • βœ… Cache - Multi-backend caching
  • βœ… Consensus - Raft consensus
  • βœ… Database - SQL and NoSQL
  • βœ… Events - Event bus and sourcing
  • βœ… GraphQL - GraphQL server
  • βœ… gRPC - gRPC services
  • βœ… HLS - HTTP Live Streaming
  • βœ… Kafka - Apache Kafka
  • βœ… MCP - Model Context Protocol
  • βœ… MQTT - MQTT broker
  • βœ… Storage - Multi-backend storage
  • βœ… Streaming - WebSocket, SSE, WebRTC

In Progress (3):

  • πŸ”„ Queue - Message queue management
  • πŸ”„ Search - Full-text search
  • πŸ”„ orpc - ORPC transport protocol

πŸ§ͺ Examples

The examples/ directory contains production-ready examples:


🀝 Contributing

We welcome contributions! Please see CONTRIBUTING.md for guidelines.

Development Workflow
# Fork and clone
git clone https://github.com/your-username/forge.git
cd forge

# Install tools
make install-tools

# Make changes
# ...

# Run tests
make test

# Check code quality
make ci

# Commit with conventional commits
git commit -m "feat: add new feature"
Conventional Commits
feat: add new feature
fix: fix bug in router
docs: update documentation
style: format code
refactor: refactor DI container
perf: optimize routing performance
test: add tests for middleware
chore: update dependencies

πŸ“„ License

This project is licensed under the Apache License 2.0 - see the LICENSE file for details.


πŸ™ Acknowledgments

Built with ❀️ by Rex Raphael

Special thanks to:

  • Bun - SQL ORM
  • Uptrace - Observability platform
  • Chi - Router inspiration
  • All contributors and maintainers


πŸ“œ License

Forge uses a dual-licensing approach:

Forge Core & Most Extensions: MIT License

The core framework and most extensions are licensed under the MIT License - one of the most permissive open source licenses.

βœ… Use freely for:

  • Commercial products and services
  • Personal projects
  • Closed-source applications
  • Modifications and distributions

See the LICENSE file for full terms.

AI Extension: Commercial Source-Available License

The AI Extension (extensions/ai/) uses a more restrictive Commercial Source-Available License.

βœ… Free for:

  • Personal projects
  • Educational purposes
  • Research and academic use
  • Internal evaluation (90 days)

❌ Commercial license required for:

  • Production deployments
  • Commercial products/services
  • Revenue-generating applications

See extensions/ai/LICENSE for full terms or LICENSING.md for the complete licensing guide.

Need a commercial license? Contact: licensing@xraph.com


πŸ“ˆ Roadmap

v2.1 (Q1 2025)
  • Complete remaining extensions (Queue, Search, orpc)
  • Enhanced AI agent orchestration
  • Real-time collaboration features
  • Advanced monitoring dashboard
v2.2 (Q2 2025)
  • Kubernetes operator
  • Helm charts and deployment automation
  • Advanced caching strategies
  • Performance optimization pass
v3.0 (Q3 2025)
  • TypeScript/Node.js runtime
  • Multi-language code generation
  • Enhanced observability platform
  • Enterprise features (SLA, auditing, compliance)

Ready to build? Get Started β†’

Documentation ΒΆ

Index ΒΆ

Constants ΒΆ

View Source
const (
	ChangeTypeSet    = config.ChangeTypeSet
	ChangeTypeUpdate = config.ChangeTypeUpdate
	ChangeTypeDelete = config.ChangeTypeDelete
	ChangeTypeReload = config.ChangeTypeReload
)

Constants.

View Source
const (
	ValidationModePermissive = config.ValidationModePermissive
	ValidationModeStrict     = config.ValidationModeStrict
	ValidationModeLoose      = config.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 ConfigKey = "config"

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

Variables ΒΆ

View Source
var (
	NewManager        = config.NewManager
	NewSourceRegistry = config.NewSourceRegistry
	NewValidator      = config.NewValidator
	NewWatcher        = config.NewWatcher
	NewSecretsManager = config.NewSecretsManager

	// Environment Variable Source Constructors
	NewEnvSource = sources.NewEnvSource

	// Auto-Discovery Functions
	DiscoverAndLoadConfigs     = config.DiscoverAndLoadConfigs
	DefaultAutoDiscoveryConfig = config.DefaultAutoDiscoveryConfig
)
View Source
var (
	WithDefault   = config.WithDefault
	WithRequired  = config.WithRequired
	WithValidator = config.WithValidator
	WithTransform = config.WithTransform
	WithOnMissing = config.WithOnMissing
	AllowEmpty    = config.AllowEmpty
	WithCacheKey  = config.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 (
	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 (
	// Basic types.
	String  = logger.String
	Int     = logger.Int
	Int8    = logger.Int8
	Int16   = logger.Int16
	Int32   = logger.Int32
	Int64   = logger.Int64
	Uint    = logger.Uint
	Uint8   = logger.Uint8
	Uint16  = logger.Uint16
	Uint32  = logger.Uint32
	Uint64  = logger.Uint64
	Float32 = logger.Float32
	Float64 = logger.Float64
	Bool    = logger.Bool

	// Time and duration.
	Time     = logger.Time
	Duration = logger.Duration

	// Error.
	Error = logger.Error

	// Advanced.
	Stringer = logger.Stringer
	Any      = logger.Any
	Stack    = logger.Stack
	Strings  = logger.Strings

	// HTTP fields.
	HTTPMethod    = logger.HTTPMethod
	HTTPStatus    = logger.HTTPStatus
	HTTPPath      = logger.HTTPPath
	HTTPURL       = logger.HTTPURL
	HTTPUserAgent = logger.HTTPUserAgent

	// Database fields.
	DatabaseQuery = logger.DatabaseQuery
	DatabaseTable = logger.DatabaseTable
	DatabaseRows  = logger.DatabaseRows

	// Service fields.
	ServiceName        = logger.ServiceName
	ServiceVersion     = logger.ServiceVersion
	ServiceEnvironment = logger.ServiceEnvironment

	// Context fields.
	RequestID     = logger.RequestID
	TraceID       = logger.TraceID
	UserID        = logger.UserID
	ContextFields = logger.ContextFields

	// Custom.
	Custom = logger.Custom
	Lazy   = logger.Lazy
)

Re-export field constructors.

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 (
	ErrExtensionNotRegistered = errors.New("extension not registered with app")
)

Extension-specific errors.

View Source
var NewServiceError = errors.NewServiceError

Re-export error constructors for backward compatibility.

Functions ΒΆ

func Must ΒΆ

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

Must resolves or panics - use only during startup.

func MustGet ΒΆ

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

MustGet returns a value or panics if not found.

func MustResolveReady ΒΆ added in v0.8.0

func MustResolveReady[T any](ctx context.Context, c Container, name string) T

MustResolveReady resolves or panics, ensuring the service is started first. Use only during startup/registration phase.

func MustScope ΒΆ

func MustScope[T any](s Scope, name string) T

MustScope resolves from scope or panics.

func Provide ΒΆ added in v0.8.0

func Provide[T any](c Container, name string, args ...any) error

Provide registers a service with typed dependency injection. It accepts InjectOption arguments followed by a factory function.

The factory function receives the resolved dependencies in order and returns the service instance and an optional error.

Usage:

forge.Provide[*UserService](c, "userService",
    forge.Inject[*bun.DB]("database"),
    forge.Inject[Logger]("logger"),
    forge.LazyInject[*Cache]("cache"),
    func(db *bun.DB, logger Logger, cache *forge.LazyRef[*Cache]) (*UserService, error) {
        return &UserService{db, logger, cache}, nil
    },
)

func ProvideWithOpts ΒΆ added in v0.8.0

func ProvideWithOpts[T any](c Container, name string, opts []RegisterOption, args ...any) error

ProvideWithOpts is like Provide but accepts additional RegisterOptions.

func RegisterInterface ΒΆ

func RegisterInterface[I, T any](c Container, name string, factory func(Container) (T, error), opts ...RegisterOption) error

RegisterInterface registers an implementation as an interface Supports all lifecycle options (Singleton, Scoped, Transient).

func RegisterScoped ΒΆ

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

RegisterScoped is a convenience wrapper for request-scoped services.

func RegisterScopedInterface ΒΆ

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

RegisterScopedInterface is a convenience wrapper.

func RegisterScopedWith ΒΆ added in v0.8.0

func RegisterScopedWith[T any](c Container, name string, args ...any) error

RegisterScopedWith registers a scoped service with typed dependency injection. Accepts InjectOption arguments followed by a factory function.

Usage:

forge.RegisterScopedWith[*Session](c, "session",
    forge.Inject[*User]("user"),
    func(user *User) (*Session, error) {
        return &Session{user: user}, nil
    },
)

func RegisterSingleton ΒΆ

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

RegisterSingleton is a convenience wrapper for singleton services.

func RegisterSingletonInterface ΒΆ

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

RegisterSingletonInterface is a convenience wrapper.

func RegisterSingletonWith ΒΆ added in v0.8.0

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

RegisterSingletonWith registers a singleton service with typed dependency injection. Accepts InjectOption arguments followed by a factory function.

Usage:

forge.RegisterSingletonWith[*UserService](c, "userService",
    forge.Inject[*bun.DB]("database"),
    func(db *bun.DB) (*UserService, error) {
        return &UserService{db: db}, nil
    },
)

func RegisterTransient ΒΆ

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

RegisterTransient is a convenience wrapper for transient services.

func RegisterTransientInterface ΒΆ

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

RegisterTransientInterface is a convenience wrapper.

func RegisterTransientWith ΒΆ added in v0.8.0

func RegisterTransientWith[T any](c Container, name string, args ...any) error

RegisterTransientWith registers a transient service with typed dependency injection. Accepts InjectOption arguments followed by a factory function.

Usage:

forge.RegisterTransientWith[*Request](c, "request",
    forge.Inject[*Context]("ctx"),
    func(ctx *Context) (*Request, error) {
        return &Request{ctx: ctx}, nil
    },
)

func RegisterValue ΒΆ

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

RegisterValue registers a pre-built instance (always singleton).

func Resolve ΒΆ

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

Resolve with type safety.

func ResolveReady ΒΆ added in v0.8.0

func ResolveReady[T any](ctx context.Context, c Container, name string) (T, error)

ResolveReady resolves a service with type safety, ensuring it and its dependencies are started first. This is useful during extension Register() phase when you need a dependency to be fully initialized before use.

Example usage in an extension's Register() method:

func (e *MyExtension) Register(app forge.App) error {
    ctx := context.Background()
    dbManager, err := forge.ResolveReady[*database.DatabaseManager](ctx, app.Container(), database.ManagerKey)
    if err != nil {
        return fmt.Errorf("database required: %w", err)
    }
    // dbManager is now fully started with open connections
    e.redis, _ = dbManager.Redis("cache")
    return nil
}

func ResolveScope ΒΆ

func ResolveScope[T any](s Scope, name string) (T, error)

ResolveScope is a helper for resolving from a scope.

func SafeGet ΒΆ

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

SafeGet returns a value with type checking.

Types ΒΆ

type App ΒΆ

type App interface {
	// Core components
	Container() Container
	Router() Router
	Config() ConfigManager
	Logger() Logger
	Metrics() Metrics
	HealthManager() HealthManager
	LifecycleManager() LifecycleManager

	// Lifecycle
	Start(ctx context.Context) error
	Stop(ctx context.Context) error
	Run() error // Blocks until shutdown signal

	// Registration
	RegisterService(name string, factory Factory, opts ...RegisterOption) error
	RegisterController(controller Controller) error
	RegisterExtension(ext Extension) error

	// Lifecycle hooks - convenience methods
	RegisterHook(phase LifecyclePhase, hook LifecycleHook, opts LifecycleHookOptions) error
	RegisterHookFn(phase LifecyclePhase, name string, hook LifecycleHook) error

	// Information
	Name() string
	Version() string
	Environment() string
	StartTime() time.Time
	Uptime() time.Duration

	// Extensions
	Extensions() []Extension
	GetExtension(name string) (Extension, error)
}

App represents a Forge application with lifecycle management.

func 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

	ErrorHandler ErrorHandler

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

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

	// Extensions
	Extensions []Extension // Extensions to register with the app

	// Config Auto-Discovery
	// If ConfigManager is not provided, these options control auto-discovery
	EnableConfigAutoDiscovery bool     // Enable automatic config file discovery (default: true)
	ConfigSearchPaths         []string // Paths to search for config files (default: current directory)
	ConfigBaseNames           []string // Base config file names (default: ["config.yaml", "config.yml"])
	ConfigLocalNames          []string // Local config file names (default: ["config.local.yaml", "config.local.yml"])
	EnableAppScopedConfig     bool     // Enable app-scoped config extraction for monorepos (default: true)

	// Environment Variable Config Sources
	// These options control how environment variables are loaded as config sources
	EnableEnvConfig  bool   // Enable loading config from environment variables (default: true)
	EnvPrefix        string // Prefix for environment variables (default: app name uppercase, e.g., "MYAPP_")
	EnvSeparator     string // Separator for nested keys in env vars (default: "_")
	EnvOverridesFile bool   // Whether env vars override file config values (default: true)
}

AppConfig configures the application.

func DefaultAppConfig ΒΆ

func DefaultAppConfig() AppConfig

DefaultAppConfig returns a default application configuration.

type AppInfo ΒΆ

type AppInfo struct {
	Name        string          `json:"name"`
	Version     string          `json:"version"`
	Description string          `json:"description"`
	Environment string          `json:"environment"`
	StartTime   time.Time       `json:"start_time"`
	Uptime      time.Duration   `json:"uptime"`
	GoVersion   string          `json:"go_version"`
	Services    []string        `json:"services"`
	Routes      int             `json:"routes"`
	Extensions  []ExtensionInfo `json:"extensions,omitempty"`
}

AppInfo represents application information returned by /_/info endpoint.

type AppOption ΒΆ added in v0.5.0

type AppOption func(*AppConfig)

AppOption is a functional option for AppConfig.

func WithAppConfigManager ΒΆ added in v0.5.0

func WithAppConfigManager(configManager ConfigManager) AppOption

WithAppConfigManager sets the config manager.

func WithAppDescription ΒΆ added in v0.5.0

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

WithAppConfigManager sets the config manager.

func WithAppMetricsConfig ΒΆ added in v0.5.0

func WithAppMetricsConfig(config MetricsConfig) AppOption

WithAppMetricsConfig sets the metrics configuration.

func WithAppName ΒΆ added in v0.5.0

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

type AsyncAPIChannel ΒΆ

type AsyncAPIChannel = shared.AsyncAPIChannel

AsyncAPIChannel represents a channel in the AsyncAPI spec.

type AsyncAPIChannelBindings ΒΆ

type AsyncAPIChannelBindings = shared.AsyncAPIChannelBindings

AsyncAPIChannelBindings contains protocol-specific channel bindings.

type AsyncAPIChannelReference ΒΆ

type AsyncAPIChannelReference = shared.AsyncAPIChannelReference

AsyncAPIChannelReference references a channel.

type AsyncAPIComponents ΒΆ

type AsyncAPIComponents = shared.AsyncAPIComponents

AsyncAPIComponents holds reusable objects for the API spec.

type AsyncAPIConfig ΒΆ

type AsyncAPIConfig = shared.AsyncAPIConfig

AsyncAPIConfig configures AsyncAPI 3.0.0 generation.

type AsyncAPICorrelationID ΒΆ

type AsyncAPICorrelationID = shared.AsyncAPICorrelationID

AsyncAPICorrelationID specifies a correlation ID for request-reply patterns.

type AsyncAPIInfo ΒΆ

type AsyncAPIInfo = shared.AsyncAPIInfo

AsyncAPIInfo provides metadata about the API.

type AsyncAPIMessage ΒΆ

type AsyncAPIMessage = shared.AsyncAPIMessage

AsyncAPIMessage represents a message in the AsyncAPI spec.

type AsyncAPIMessageBindings ΒΆ

type AsyncAPIMessageBindings = shared.AsyncAPIMessageBindings

AsyncAPIMessageBindings contains protocol-specific message bindings.

type AsyncAPIMessageExample ΒΆ

type AsyncAPIMessageExample = shared.AsyncAPIMessageExample

AsyncAPIMessageExample represents an example of a message.

type AsyncAPIMessageReference ΒΆ

type AsyncAPIMessageReference = shared.AsyncAPIMessageReference

AsyncAPIMessageReference references a message.

type AsyncAPIMessageTrait ΒΆ

type AsyncAPIMessageTrait = shared.AsyncAPIMessageTrait

AsyncAPIMessageTrait represents reusable message characteristics.

type AsyncAPIOAuthFlows ΒΆ

type AsyncAPIOAuthFlows = shared.AsyncAPIOAuthFlows

AsyncAPIOAuthFlows defines OAuth 2.0 flows.

type AsyncAPIOperation ΒΆ

type AsyncAPIOperation = shared.AsyncAPIOperation

AsyncAPIOperation represents an operation in the AsyncAPI spec.

type AsyncAPIOperationBindings ΒΆ

type AsyncAPIOperationBindings = shared.AsyncAPIOperationBindings

AsyncAPIOperationBindings contains protocol-specific operation bindings.

type AsyncAPIOperationReply ΒΆ

type AsyncAPIOperationReply = shared.AsyncAPIOperationReply

AsyncAPIOperationReply represents the reply configuration for an operation.

type AsyncAPIOperationReplyAddress ΒΆ

type AsyncAPIOperationReplyAddress = shared.AsyncAPIOperationReplyAddress

AsyncAPIOperationReplyAddress represents the reply address.

type AsyncAPIOperationTrait ΒΆ

type AsyncAPIOperationTrait = shared.AsyncAPIOperationTrait

AsyncAPIOperationTrait represents reusable operation characteristics.

type AsyncAPIParameter ΒΆ

type AsyncAPIParameter = shared.AsyncAPIParameter

AsyncAPIParameter represents a parameter in channel address.

type AsyncAPISecurityRequirement ΒΆ

type AsyncAPISecurityRequirement = shared.AsyncAPISecurityRequirement

AsyncAPISecurityRequirement lists required security schemes.

type AsyncAPISecurityScheme ΒΆ

type AsyncAPISecurityScheme = shared.AsyncAPISecurityScheme

AsyncAPISecurityScheme defines a security scheme.

type AsyncAPIServer ΒΆ

type AsyncAPIServer = shared.AsyncAPIServer

AsyncAPIServer represents a server in the AsyncAPI spec.

type AsyncAPIServerBindings ΒΆ

type AsyncAPIServerBindings = shared.AsyncAPIServerBindings

AsyncAPIServerBindings contains protocol-specific server bindings.

type AsyncAPIServerReference ΒΆ

type AsyncAPIServerReference = shared.AsyncAPIServerReference

AsyncAPIServerReference references a server.

type AsyncAPISpec ΒΆ

type AsyncAPISpec = shared.AsyncAPISpec

AsyncAPISpec represents the complete AsyncAPI 3.0.0 specification.

type AsyncAPITag ΒΆ

type AsyncAPITag = shared.AsyncAPITag

AsyncAPITag represents a tag in the AsyncAPI spec.

type AutoDiscoveryConfig ΒΆ added in v0.8.3

type AutoDiscoveryConfig = config.AutoDiscoveryConfig

Auto-Discovery Types.

type AutoDiscoveryResult ΒΆ added in v0.8.3

type AutoDiscoveryResult = config.AutoDiscoveryResult

Auto-Discovery Types.

type BaseExtension ΒΆ

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

BaseExtension provides common functionality for implementing extensions. Extensions can embed BaseExtension to get standard implementations of common methods.

Example usage:

type MyExtension struct {
    *forge.BaseExtension
    config MyConfig
    client *MyClient
}

func NewMyExtension(config MyConfig) forge.Extension {
    return &MyExtension{
        BaseExtension: forge.NewBaseExtension("my-ext", "1.0.0", "My extension"),
        config:        config,
    }
}

func NewBaseExtension ΒΆ

func NewBaseExtension(name, version, description string) *BaseExtension

NewBaseExtension creates a new base extension with the given identity.

func (*BaseExtension) App ΒΆ

func (e *BaseExtension) App() App

App returns the app instance this extension is registered with.

func (*BaseExtension) Dependencies ΒΆ

func (e *BaseExtension) Dependencies() []string

Dependencies returns the extension dependencies.

func (*BaseExtension) Description ΒΆ

func (e *BaseExtension) Description() string

Description returns the extension description.

func (*BaseExtension) Health ΒΆ

func (e *BaseExtension) Health(ctx context.Context) error

Health is a default implementation that always returns healthy. Extensions should override this to implement actual health checks.

func (*BaseExtension) IsStarted ΒΆ

func (e *BaseExtension) IsStarted() bool

IsStarted returns true if the extension has been started.

func (*BaseExtension) LoadConfig ΒΆ

func (e *BaseExtension) LoadConfig(
	key string,
	target any,
	programmaticConfig any,
	defaults any,
	requireConfig bool,
) error

LoadConfig loads configuration for this extension from ConfigManager.

It tries the following keys in order:

  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) SetDependencies ΒΆ

func (e *BaseExtension) SetDependencies(deps []string)

SetDependencies sets the extension dependencies.

func (*BaseExtension) SetLogger ΒΆ

func (e *BaseExtension) SetLogger(logger Logger)

SetLogger sets the logger for this extension.

func (*BaseExtension) SetMetrics ΒΆ

func (e *BaseExtension) SetMetrics(metrics Metrics)

SetMetrics sets the metrics for this extension.

func (*BaseExtension) Start ΒΆ

func (e *BaseExtension) Start(ctx context.Context) error

Start is a default implementation that does nothing. Extensions should override this to start their services.

func (*BaseExtension) Stop ΒΆ

func (e *BaseExtension) Stop(ctx context.Context) error

Stop is a default implementation that does nothing. Extensions should override this to stop their services.

func (*BaseExtension) Version ΒΆ

func (e *BaseExtension) Version() string

Version returns the extension version.

type BindOptions ΒΆ

type BindOptions = configcore.BindOptions

Configuration Options.

func DefaultBindOptions ΒΆ

func DefaultBindOptions() BindOptions

DefaultBindOptions returns default bind options.

type BunRouterAdapter ΒΆ

type BunRouterAdapter = router.BunRouterAdapter

BunRouterAdapter wraps uptrace/bunrouter.

type CallbackConfig ΒΆ

type CallbackConfig = router.CallbackConfig

CallbackConfig defines a callback (webhook) for an operation.

func NewCompletionCallbackConfig ΒΆ

func NewCompletionCallbackConfig(callbackURLExpression string, resultSchema any) CallbackConfig

NewCompletionCallbackConfig creates a callback config for async operation completion.

func NewEventCallbackConfig ΒΆ

func NewEventCallbackConfig(callbackURLExpression string, eventSchema any) CallbackConfig

NewEventCallbackConfig creates a callback config for event notifications.

func NewStatusCallbackConfig ΒΆ

func NewStatusCallbackConfig(callbackURLExpression string, statusSchema any) CallbackConfig

NewStatusCallbackConfig creates a callback config for status updates.

type CallbackOperation ΒΆ

type CallbackOperation = router.CallbackOperation

CallbackOperation defines an operation that will be called back.

func NewCallbackOperation ΒΆ

func NewCallbackOperation(summary, description string) *CallbackOperation

NewCallbackOperation creates a new callback operation.

type ChangeType ΒΆ

type ChangeType = config.ChangeType

Configuration Changes.

type Components ΒΆ

type Components = shared.Components

Components holds reusable objects for the API spec.

type ConfigChange ΒΆ

type ConfigChange = config.ConfigChange

Configuration Changes.

type ConfigErrorHandler ΒΆ

type ConfigErrorHandler interface {
	// HandleError handles an error
	HandleError(ctx Context, err error) error

	// ShouldRetry determines if an operation should be retried
	ShouldRetry(err error) bool

	// GetRetryDelay returns the delay before retrying
	GetRetryDelay(attempt int, err error) time.Duration
}

ConfigErrorHandler defines how errors should be handled in the config system.

type ConfigManager ΒΆ

type ConfigManager = configcore.ConfigManager

Configuration Manager.

func GetConfigManager ΒΆ added in v0.5.0

func GetConfigManager(c Container) (ConfigManager, error)

GetConfigManager resolves the config manager from the container Returns the config manager instance and an error if resolution fails.

func NewDefaultConfigManager ΒΆ

func NewDefaultConfigManager(
	l logger.Logger,
	m Metrics,
	e ErrorHandler,
) ConfigManager

Helper to create a default config manager (stub for now).

type ConfigSource ΒΆ

type ConfigSource = config.ConfigSource

Configuration Sources.

type ConfigSourceFactory ΒΆ

type ConfigSourceFactory = config.ConfigSourceFactory

Configuration Sources.

type ConfigSourceOptions ΒΆ

type ConfigSourceOptions = config.ConfigSourceOptions

Configuration Sources.

type Configurable ΒΆ

type Configurable = shared.Configurable

Configurable is optional for services that need configuration.

type ConfigurableExtension ΒΆ

type ConfigurableExtension interface {
	Extension
	// Configure configures the extension with the provided config object
	Configure(config any) error
}

ConfigurableExtension is an optional interface for extensions that support configuration.

type Connection ΒΆ

type Connection = router.Connection

Connection represents a WebSocket connection.

type Contact ΒΆ

type Contact = shared.Contact

Contact represents contact information.

type Container ΒΆ

type Container = shared.Container

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 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 Encoding ΒΆ

type Encoding = shared.Encoding

Encoding defines encoding for a property.

type EnvSourceConfig ΒΆ added in v0.8.3

type EnvSourceConfig = sources.EnvSourceConfig

Environment Variable Source Types.

type EnvSourceOptions ΒΆ added in v0.8.3

type EnvSourceOptions = sources.EnvSourceOptions

Environment Variable Source Types.

type ErrorHandler ΒΆ

type ErrorHandler = shared.ErrorHandler

ErrorHandler handles errors from handlers.

func NewDefaultErrorHandler ΒΆ

func NewDefaultErrorHandler(l Logger) ErrorHandler

NewDefaultErrorHandler creates a default error handler.

type 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 = shared.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 Gauge ΒΆ

type Gauge = shared.Gauge

Gauge tracks values that can go up or down.

type GetOption ΒΆ

type GetOption = configcore.GetOption

Configuration Options.

type GetOptions ΒΆ

type GetOptions = configcore.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

Group option constructors.

func WithGroupRequiredScopes ΒΆ

func WithGroupRequiredScopes(scopes ...string) GroupOption

WithGroupRequiredScopes sets required scopes for all routes in a group.

func WithGroupSchemaExclude ΒΆ added in v0.7.0

func WithGroupSchemaExclude() GroupOption

WithGroupSchemaExclude excludes all routes in this group from schema generation (OpenAPI, AsyncAPI, and oRPC).

This is useful for internal/debug/admin route groups that shouldn't appear in public API documentation.

Example:

// Create an internal admin group
adminGroup := router.Group("/admin", forge.WithGroupSchemaExclude())
adminGroup.GET("/users", listUsers)
adminGroup.DELETE("/cache", flushCache)
// All routes in this group are excluded from schemas

func WithGroupTags ΒΆ

func WithGroupTags(tags ...string) GroupOption

type HTTPChannelBinding ΒΆ

type HTTPChannelBinding = shared.HTTPChannelBinding

HTTPChannelBinding represents HTTP-specific channel configuration.

type HTTPError ΒΆ

type HTTPError = errors.HTTPError

Re-export HTTP error types and constructors 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 HealthManager ΒΆ

type HealthManager = shared.HealthManager

HealthManager performs health checks across the system.

func GetHealthManager ΒΆ added in v0.5.0

func GetHealthManager(c Container) (HealthManager, error)

GetHealthManager resolves the health manager from the container Returns the health manager instance and an error if resolution fails.

func NewHealthManager ΒΆ

func NewHealthManager(config *health.HealthConfig, logger Logger, metrics shared.Metrics, container shared.Container) HealthManager

NewHealthManager creates a new health manager.

func NewNoOpHealthManager ΒΆ

func NewNoOpHealthManager() HealthManager

NewNoOpHealthManager creates a no-op health manager.

type HealthReport ΒΆ

type HealthReport = shared.HealthReport

HealthReport contains results of all checks.

type HealthResult ΒΆ

type HealthResult = shared.HealthResult

HealthResult represents the result of a health check.

type HealthStatus ΒΆ

type HealthStatus = shared.HealthStatus

HealthStatus represents overall health.

type 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 InjectOption ΒΆ added in v0.8.0

type InjectOption = di.InjectOption

InjectOption represents a dependency injection option with type information.

func Inject ΒΆ added in v0.8.0

func Inject[T any](name string) InjectOption

Inject creates an eager injection option for a dependency. The dependency is resolved immediately when the service is created.

Usage:

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

func LazyInject ΒΆ added in v0.8.0

func LazyInject[T any](name string) InjectOption

LazyInject creates a lazy injection option for a dependency. The dependency is resolved on first access via Lazy[T].Get().

func LazyOptionalInject ΒΆ added in v0.8.0

func LazyOptionalInject[T any](name string) InjectOption

LazyOptionalInject creates a lazy optional injection option. The dependency is resolved on first access and returns nil if not found.

func OptionalInject ΒΆ added in v0.8.0

func OptionalInject[T any](name string) InjectOption

OptionalInject creates an optional injection option for a dependency. The dependency is resolved immediately but returns nil if not found.

func ProviderInject ΒΆ added in v0.8.0

func ProviderInject[T any](name string) InjectOption

ProviderInject creates an injection option for a transient dependency provider.

type InternalExtension ΒΆ added in v0.7.0

type InternalExtension = router.InternalExtension

InternalExtension is re-exported from router package for convenience

type LazyAny ΒΆ added in v0.8.0

type LazyAny = di.LazyAny

LazyAny is a non-generic lazy wrapper used with LazyInject. Use this type in your factory function when using LazyInject[T].

type LazyRef ΒΆ added in v0.8.0

type LazyRef[T any] = di.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 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 ManagerConfig ΒΆ

type ManagerConfig = config.ManagerConfig

Manager Configuration.

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 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 MetricsConfig ΒΆ

type MetricsConfig = shared.MetricsConfig

MetricsConfig configures metrics collection.

func DefaultMetricsConfig ΒΆ

func DefaultMetricsConfig() MetricsConfig

DefaultMetricsConfig returns default metrics configuration.

type Middleware ΒΆ

type Middleware = router.Middleware

Middleware wraps HTTP handlers.

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 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 OptionalLazyAny ΒΆ added in v0.8.0

type OptionalLazyAny = di.OptionalLazyAny

OptionalLazyAny is a non-generic optional lazy wrapper used with LazyOptionalInject. Use this type in your factory function when using LazyOptionalInject[T].

type OptionalLazyRef ΒΆ added in v0.8.0

type OptionalLazyRef[T any] = di.OptionalLazy[T]

OptionalLazyRef wraps an optional dependency that is resolved on first access. Returns nil without error if the dependency is not found.

func NewOptionalLazyRef ΒΆ added in v0.8.0

func NewOptionalLazyRef[T any](c Container, name string) *OptionalLazyRef[T]

NewOptionalLazyRef creates a new optional lazy dependency wrapper.

type 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 ProviderRef ΒΆ added in v0.8.0

type ProviderRef[T any] = di.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

FromHTTPMiddleware converts a legacy http.Handler middleware to a ForgeMiddleware This allows existing http.Handler middlewares to work with forge handlers.

func ToPureMiddleware ΒΆ added in v0.5.0

func ToPureMiddleware(m Middleware, container Container, errorHandler ErrorHandler) PureMiddleware

ToPureMiddleware converts a Middleware (forge middleware) to a PureMiddleware (http middleware) This allows forge middlewares to work with http.Handler based systems.

type RegisterOption ΒΆ

type RegisterOption = shared.RegisterOption

RegisterOption is a configuration option for service registration.

func Scoped ΒΆ

func Scoped() RegisterOption

Scoped makes the service live for the duration of a scope.

func Singleton ΒΆ

func Singleton() RegisterOption

Singleton makes the service a singleton (default).

func Transient ΒΆ

func Transient() RegisterOption

Transient makes the service created on each resolve.

func WithDIMetadata ΒΆ

func WithDIMetadata(key, value string) RegisterOption

WithDIMetadata adds diagnostic metadata to DI service registration.

func WithDependencies ΒΆ

func WithDependencies(deps ...string) RegisterOption

WithDependencies declares explicit dependencies.

func WithGroup ΒΆ

func WithGroup(group string) RegisterOption

WithGroup adds service to a named group.

type RequestBody ΒΆ

type RequestBody = shared.RequestBody

RequestBody describes a single request body.

type RequestBodyDef ΒΆ

type RequestBodyDef = router.RequestBodyDef

RequestBodyDef defines a request body.

type 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 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 WithErrorResponses ΒΆ

func WithErrorResponses() RouteOption

WithErrorResponses adds standard HTTP error responses to a route.

func WithExtension ΒΆ

func WithExtension(name string, ext Extension) RouteOption

func WithExtensionExclusion ΒΆ added in v0.7.0

func WithExtensionExclusion(ext Extension) RouteOption

WithExtensionExclusion checks if an extension implements InternalExtension and automatically excludes its routes from schema generation if needed.

This is a helper function for extensions to use when registering routes.

Example:

func (e *DebugExtension) Start(ctx context.Context) error {
    router := e.app.Router()
    opts := forge.WithExtensionExclusion(e)

    router.GET("/debug/status", statusHandler, opts)
    router.GET("/debug/metrics", metricsHandler, opts)
    return nil
}

func WithExternalDocs ΒΆ

func WithExternalDocs(description, url string) RouteOption

WithExternalDocs adds external documentation link.

func WithFileUploadResponse ΒΆ

func WithFileUploadResponse(statusCode int) RouteOption

WithFileUploadResponse creates a response for file upload success.

func WithHeaderSchema ΒΆ

func WithHeaderSchema(schemaType any) RouteOption

WithHeaderSchema sets the header parameters schema for OpenAPI generation.

func WithListResponse ΒΆ

func WithListResponse(itemType any, statusCode int) RouteOption

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

func WithMessageContentType ΒΆ

func WithMessageContentType(contentType string) RouteOption

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

func WithMessageExample ΒΆ

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

WithMessageExample adds a single message example.

func WithMessageExamples ΒΆ

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

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

func WithMessageHeaders ΒΆ

func WithMessageHeaders(headersSchema any) RouteOption

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

func WithMetadata ΒΆ

func WithMetadata(key string, value any) RouteOption

func WithMethod ΒΆ added in v0.8.0

func WithMethod(method string) RouteOption

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

Example:

// Default GET behavior
router.SSE("/events", handler)

// Override to POST
router.SSE("/events", handler, forge.WithMethod(http.MethodPost))

// POST SSE with request body
router.EventStream("/stream", streamHandler,
    forge.WithMethod(http.MethodPost),
    forge.WithTags("streaming"),
)

func WithMiddleware ΒΆ

func WithMiddleware(mw ...Middleware) RouteOption

func WithName ΒΆ

func WithName(name string) RouteOption

Route option constructors.

func WithNoContentResponse ΒΆ

func WithNoContentResponse() RouteOption

WithNoContentResponse creates a 204 No Content response.

func WithORPCExclude ΒΆ

func WithORPCExclude() RouteOption

WithORPCExclude excludes this route from oRPC auto-exposure. Use this to prevent specific routes from being exposed as JSON-RPC methods.

Example:

router.GET("/internal/debug", debugHandler,
    forge.WithORPCExclude(),
)

func WithORPCMethod ΒΆ

func WithORPCMethod(methodName string) RouteOption

WithORPCMethod sets a custom JSON-RPC method name for this route. By default, method names are generated from the HTTP method and path.

Example:

router.GET("/users/:id", getUserHandler,
    forge.WithORPCMethod("user.get"),
)

func WithORPCParams ΒΆ

func WithORPCParams(schema any) RouteOption

WithORPCParams sets the params schema for OpenRPC schema generation. The schema should be a struct or map describing the expected parameters.

Example:

type UserGetParams struct {
    ID string `json:"id"`
}
router.GET("/users/:id", getUserHandler,
    forge.WithORPCParams(&orpc.ParamsSchema{
        Type: "object",
        Properties: map[string]*orpc.PropertySchema{
            "id": {Type: "string", Description: "User ID"},
        },
        Required: []string{"id"},
    }),
)

func WithORPCPrimaryResponse ΒΆ

func WithORPCPrimaryResponse(statusCode int) RouteOption

WithORPCPrimaryResponse sets which response status code should be used as the primary oRPC result schema when multiple success responses (200, 201, etc.) are defined. This is useful when you have both 200 and 201 responses and want to explicitly choose one.

By default, oRPC uses method-aware selection:

  • POST: Prefers 201, then 200
  • GET: Prefers 200
  • PUT/PATCH/DELETE: Prefers 200

Example:

router.POST("/users", createUserHandler,
    forge.WithResponseSchema(200, "Updated user", UserResponse{}),
    forge.WithResponseSchema(201, "Created user", UserResponse{}),
    forge.WithORPCPrimaryResponse(200), // Explicitly use 200
)

func WithORPCResult ΒΆ

func WithORPCResult(schema any) RouteOption

WithORPCResult sets the result schema for OpenRPC schema generation. The schema should be a struct or map describing the expected result.

Example:

router.GET("/users/:id", getUserHandler,
    forge.WithORPCResult(&orpc.ResultSchema{
        Type: "object",
        Description: "User details",
    }),
)

func WithORPCTags ΒΆ

func WithORPCTags(tags ...string) RouteOption

WithORPCTags adds custom tags for OpenRPC schema organization. These tags are used in addition to the route's regular tags.

Example:

router.GET("/users/:id", getUserHandler,
    forge.WithORPCTags("users", "read"),
)

func WithOpenAPIExclude ΒΆ added in v0.7.0

func WithOpenAPIExclude() RouteOption

WithOpenAPIExclude excludes this route from OpenAPI schema generation. Use this to prevent specific routes from appearing in OpenAPI documentation.

Example:

router.GET("/internal/health", healthHandler,
    forge.WithOpenAPIExclude(),
)

func WithOperationID ΒΆ

func WithOperationID(id string) RouteOption

func WithPaginatedResponse ΒΆ

func WithPaginatedResponse(itemType any, statusCode int) RouteOption

WithPaginatedResponse creates a route option for paginated list responses.

func WithParameter ΒΆ

func WithParameter(name, in, description string, required bool, example any) RouteOption

WithParameter adds a parameter definition.

func WithQuerySchema ΒΆ

func WithQuerySchema(schemaType any) RouteOption

WithQuerySchema sets the query parameters schema for OpenAPI generation.

func WithRequestBody ΒΆ

func WithRequestBody(description string, required bool, example any) RouteOption

WithRequestBody adds request body documentation.

func WithRequestBodySchema ΒΆ

func WithRequestBodySchema(schemaOrType any) RouteOption

WithRequestBodySchema sets only the request body schema for OpenAPI generation. Use this for explicit body-only schemas when you need separate schemas for different parts.

func WithRequestContentTypes ΒΆ

func WithRequestContentTypes(types ...string) RouteOption

WithRequestContentTypes specifies the content types for request body.

func WithRequestExample ΒΆ

func WithRequestExample(name string, example any) RouteOption

WithRequestExample adds an example for the request body.

func WithRequestSchema ΒΆ

func WithRequestSchema(schemaOrType any) RouteOption

WithRequestSchema sets the unified request schema for OpenAPI generation. This is the recommended approach that automatically classifies struct fields based on tags:

  • path:"paramName" - Path parameter
  • query:"paramName" - Query parameter
  • header:"HeaderName" - Header parameter
  • body:"" or json:"fieldName" - Request body field

Example:

type CreateUserRequest struct {
    TenantID string `path:"tenantId" description:"Tenant ID" format:"uuid"`
    DryRun   bool   `query:"dryRun" description:"Preview mode"`
    APIKey   string `header:"X-API-Key" description:"API Key"`
    Name     string `json:"name" body:"" description:"User name" minLength:"1"`
    Email    string `json:"email" body:"" description:"Email" format:"email"`
}

If the struct has no path/query/header tags, it's treated as body-only for backward compatibility.

func WithRequiredAuth ΒΆ

func WithRequiredAuth(providerName string, scopes ...string) RouteOption

WithRequiredAuth adds authentication with required scopes/permissions. The specified provider must succeed AND the auth context must have all required scopes.

Example:

router.POST("/admin/users", handler,
    forge.WithRequiredAuth("jwt", "write:users", "admin"),
)

func WithResponse ΒΆ

func WithResponse(code int, description string, example any) RouteOption

WithResponse adds a response definition to the route.

func WithResponseContentTypes ΒΆ

func WithResponseContentTypes(types ...string) RouteOption

WithResponseContentTypes specifies the content types for response body.

func WithResponseExample ΒΆ

func WithResponseExample(statusCode int, name string, example any) RouteOption

WithResponseExample adds an example for a specific response status code.

func WithResponseSchema ΒΆ

func WithResponseSchema(statusCode int, description string, schemaOrType any) RouteOption

WithResponseSchema sets a response schema for OpenAPI generation.

func WithSSEMessage ΒΆ

func WithSSEMessage(eventName string, schema any) RouteOption

WithSSEMessage defines a single message schema for SSE endpoints eventName: the SSE event name (e.g., "message", "update", "notification") schema: the message schema

func WithSSEMessages ΒΆ

func WithSSEMessages(messageSchemas map[string]any) RouteOption

WithSSEMessages defines message schemas for SSE endpoints messageSchemas: map of event names to their schemas SSE is receive-only (server -> client), so action is always "receive".

func WithSchemaExclude ΒΆ added in v0.7.0

func WithSchemaExclude() RouteOption

WithSchemaExclude excludes this route from all schema generation (OpenAPI, AsyncAPI, oRPC). This is a convenience method that combines all exclusion options.

Example:

router.GET("/internal/debug", debugHandler,
    forge.WithSchemaExclude(),
)

func WithSchemaRef ΒΆ

func WithSchemaRef(name string, schema any) RouteOption

WithSchemaRef adds a schema reference to components.

func WithSecurity ΒΆ

func WithSecurity(schemes ...string) RouteOption

WithSecurity sets security requirements for a route.

func WithSensitiveFieldCleaning ΒΆ added in v0.7.0

func WithSensitiveFieldCleaning() RouteOption

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

  • sensitive:"true" -> set to zero value (empty string, 0, nil)
  • sensitive:"redact" -> set to "[REDACTED]"
  • sensitive:"mask:***" -> set to custom mask "***"

Example:

type UserResponse struct {
    ID       string `json:"id"`
    Password string `json:"password" sensitive:"true"`
    APIKey   string `json:"api_key" sensitive:"redact"`
    Token    string `json:"token" sensitive:"mask:***"`
}

router.GET("/user", handler, forge.WithSensitiveFieldCleaning())

func WithServerProtocol ΒΆ

func WithServerProtocol(serverNames ...string) RouteOption

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

func WithStandardRESTResponses ΒΆ

func WithStandardRESTResponses(resourceType any) RouteOption

WithStandardRESTResponses adds standard REST CRUD responses for a resource.

func WithStrictValidation ΒΆ

func WithStrictValidation() RouteOption

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

func WithSummary ΒΆ

func WithSummary(summary string) RouteOption

func WithTags ΒΆ

func WithTags(tags ...string) RouteOption

func WithTimeout ΒΆ

func WithTimeout(d time.Duration) RouteOption

func WithValidation ΒΆ

func WithValidation(enabled bool) RouteOption

WithValidation adds validation middleware to a route.

func WithValidationErrorResponse ΒΆ

func WithValidationErrorResponse() RouteOption

WithValidationErrorResponse adds a 422 Unprocessable Entity response for validation errors.

func WithWebSocketMessages ΒΆ

func WithWebSocketMessages(sendSchema, receiveSchema any) RouteOption

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

func WithWebhook ΒΆ

func WithWebhook(name string, operation *CallbackOperation) RouteOption

WithWebhook adds a webhook definition to the OpenAPI spec.

type Router ΒΆ

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

Router option constructors.

func WithAsyncAPI ΒΆ

func WithAsyncAPI(config AsyncAPIConfig) RouterOption

WithAsyncAPI enables AsyncAPI 3.0.0 spec generation.

func WithContainer ΒΆ

func WithContainer(container Container) RouterOption

func WithErrorHandler ΒΆ

func WithErrorHandler(handler ErrorHandler) RouterOption

func WithHealth ΒΆ

func WithHealth(config HealthConfig) RouterOption

WithHealth enables health checks.

func WithLogger ΒΆ

func WithLogger(logger Logger) RouterOption

func WithMetrics ΒΆ

func WithMetrics(config MetricsConfig) RouterOption

WithMetrics enables metrics collection.

func WithOpenAPI ΒΆ

func WithOpenAPI(config OpenAPIConfig) RouterOption

WithOpenAPI enables OpenAPI 3.1.0 spec generation.

func WithRecovery ΒΆ

func WithRecovery() RouterOption

type RunnableExtension ΒΆ added in v0.4.0

type RunnableExtension interface {
	Extension

	// Run starts the extension's long-running processes.
	// This is called during PhaseAfterRun, after the HTTP server starts.
	// Run should be non-blocking - start goroutines or external processes and return.
	Run(ctx context.Context) error

	// Shutdown gracefully stops the extension's long-running processes.
	// This is called during PhaseBeforeStop, before the app shuts down.
	// Implementations should respect the context deadline for graceful shutdown.
	Shutdown(ctx context.Context) error
}

RunnableExtension is an optional interface for extensions that need to run long-running processes (goroutines, external apps, workers) alongside the app.

Extensions implementing this interface will have their Run() method called automatically during the PhaseAfterRun lifecycle phase, and their Shutdown() method called during PhaseBeforeStop.

This provides a standardized way to manage external processes, background workers, and other long-running tasks without manually registering lifecycle hooks.

Example usage:

type WorkerExtension struct {
    *forge.BaseExtension
    workerDone chan struct{}
}

func (e *WorkerExtension) Run(ctx context.Context) error {
    e.Logger().Info("starting background worker")
    go e.runWorker()
    return nil
}

func (e *WorkerExtension) Shutdown(ctx context.Context) error {
    e.Logger().Info("stopping background worker")
    close(e.workerDone)
    return nil
}

type 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 = shared.Scope

Scope represents a lifetime scope for scoped services Typically used for HTTP requests or other bounded operations.

type SecretProvider ΒΆ

type SecretProvider = config.SecretProvider

Secrets.

type SecretsConfig ΒΆ

type SecretsConfig = config.SecretsConfig

Secrets.

type SecretsManager ΒΆ

type SecretsManager = config.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

Re-export error types for backward compatibility.

type ServiceInfo ΒΆ

type ServiceInfo = shared.ServiceInfo

ServiceInfo contains diagnostic information.

type SourceConfig ΒΆ

type SourceConfig = config.SourceConfig

Configuration Sources.

type SourceEvent ΒΆ

type SourceEvent = config.SourceEvent

Configuration Sources.

type SourceEventHandler ΒΆ

type SourceEventHandler = config.SourceEventHandler

Configuration Sources.

type SourceMetadata ΒΆ

type SourceMetadata = config.SourceMetadata

Configuration Sources.

type SourceRegistry ΒΆ

type SourceRegistry = config.SourceRegistry

Configuration Sources.

type Stream ΒΆ

type Stream = router.Stream

Stream represents a Server-Sent Events stream.

type StreamConfig ΒΆ

type StreamConfig = router.StreamConfig

StreamConfig configures streaming behavior.

func DefaultStreamConfig ΒΆ

func DefaultStreamConfig() StreamConfig

DefaultStreamConfig returns default streaming configuration.

type StringMap ΒΆ added in v0.3.0

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 = config.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 = config.ValidationMode

Validation.

type ValidationOptions ΒΆ

type ValidationOptions = config.ValidationOptions

Validation.

type ValidationRule ΒΆ

type ValidationRule = config.ValidationRule

Validation.

type Validator ΒΆ

type Validator = config.Validator

Validation.

type WatchContext ΒΆ

type WatchContext = config.WatchContext

Configuration Sources.

type Watcher ΒΆ

type Watcher = config.Watcher

Watcher.

type WatcherConfig ΒΆ

type WatcherConfig = config.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
forge command
v2/cmd/forge/main.go
v2/cmd/forge/main.go
forge/config
v2/cmd/forge/config/loader.go
v2/cmd/forge/config/loader.go
forge/plugins
v2/cmd/forge/plugins/build.go
v2/cmd/forge/plugins/build.go
forge/plugins/infra
v2/cmd/forge/plugins/infra/generator.go
v2/cmd/forge/plugins/infra/generator.go
examples
ai-agents-demo command
ai-demo command
banner-demo command
cache-demo command
config-example command
context-example command
database-demo command
database-migration-docker command
Package main demonstrates that the database extension with migrations can now start successfully in Docker/CI environments without panicking.
Package main demonstrates that the database extension with migrations can now start successfully in Docker/CI environments without panicking.
events-demo command
lifecycle-hooks command
mcp-advanced command
mcp-basic command
minimal-app command
observability command
orpc_example command
service-di command
sse-streaming command
wildcard_routes command
extensions
ai
cron/core
Package core contains shared interfaces to avoid import cycles.
Package core contains shared interfaces to avoid import cycles.
cron/examples command
cron/register
Package register imports scheduler and storage implementations to register them.
Package register imports scheduler and storage implementations to register them.
database
Package database provides unified database access with support for SQL (Postgres, MySQL, SQLite) and NoSQL (MongoDB) databases.
Package database provides unified database access with support for SQL (Postgres, MySQL, SQLite) and NoSQL (MongoDB) databases.
database/migrate
Package migrate provides migration management for the database extension
Package migrate provides migration management for the database extension
mcp
storage
Package storage provides unified object storage with support for multiple backends including local filesystem, S3, GCS, and Azure Blob Storage.
Package storage provides unified object storage with support for multiple backends including local filesystem, S3, GCS, and Azure Blob Storage.
graphql module
grpc module
kafka module
mqtt module
Package farp provides Forge-specific integrations for the FARP protocol.
Package farp provides Forge-specific integrations for the FARP protocol.
examples/basic command
internal
di

Jump to

Keyboard shortcuts

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