forge

package module
v0.1.6 Latest Latest
Warning

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

Go to latest
Published: Oct 28, 2025 License: MIT Imports: 19 Imported by: 0

README ΒΆ

πŸ”¨ Forge v2

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 := forge.Must[*bun.DB](c, "db")
    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
    aiService := forge.Must[ai.Service](app.Container(), "ai")

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

Variables ΒΆ

View Source
var (
	NewManager        = config.NewManager
	NewSourceRegistry = config.NewSourceRegistry
	NewValidator      = config.NewValidator
	NewWatcher        = config.NewWatcher
	NewSecretsManager = config.NewSecretsManager
)
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
	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 = fmt.Errorf("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 MustScope ΒΆ

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

MustScope resolves from scope or panics

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

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

RegisterSingleton is a convenience wrapper

func RegisterSingletonInterface ΒΆ

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

RegisterSingletonInterface is a convenience wrapper

func RegisterTransient ΒΆ

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

RegisterTransient is a convenience wrapper

func RegisterTransientInterface ΒΆ

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

RegisterTransientInterface is a convenience wrapper

func RegisterValue ΒΆ

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

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

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

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

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

App represents a Forge application with lifecycle management

func New ΒΆ

func New(config AppConfig) App

New creates a new Forge application

func NewApp ΒΆ

func NewApp(config AppConfig) App

NewApp creates a new Forge application

type AppConfig ΒΆ

type AppConfig struct {
	// Basic info
	Name        string
	Version     string
	Description string
	Environment string // "development", "staging", "production"

	// Components
	ConfigManager ConfigManager
	Logger        Logger

	// Router options
	RouterOptions []RouterOption

	// Observability
	MetricsConfig MetricsConfig
	HealthConfig  HealthConfig

	ErrorHandler ErrorHandler

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

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

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

AppConfig configures the application

func DefaultAppConfig ΒΆ

func DefaultAppConfig() AppConfig

DefaultAppConfig returns a default application configuration

type AppInfo ΒΆ

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

AppInfo represents application information returned by /_/info endpoint

type AsyncAPIChannel ΒΆ

type AsyncAPIChannel = shared.AsyncAPIChannel

AsyncAPIChannel represents a channel in the AsyncAPI spec

type AsyncAPIChannelBindings ΒΆ

type AsyncAPIChannelBindings = shared.AsyncAPIChannelBindings

AsyncAPIChannelBindings contains protocol-specific channel bindings

type AsyncAPIChannelReference ΒΆ

type AsyncAPIChannelReference = shared.AsyncAPIChannelReference

AsyncAPIChannelReference references a channel

type AsyncAPIComponents ΒΆ

type AsyncAPIComponents = shared.AsyncAPIComponents

AsyncAPIComponents holds reusable objects for the API spec

type AsyncAPIConfig ΒΆ

type AsyncAPIConfig = shared.AsyncAPIConfig

AsyncAPIConfig configures AsyncAPI 3.0.0 generation

type AsyncAPICorrelationID ΒΆ

type AsyncAPICorrelationID = shared.AsyncAPICorrelationID

AsyncAPICorrelationID specifies a correlation ID for request-reply patterns

type AsyncAPIInfo ΒΆ

type AsyncAPIInfo = shared.AsyncAPIInfo

AsyncAPIInfo provides metadata about the API

type AsyncAPIMessage ΒΆ

type AsyncAPIMessage = shared.AsyncAPIMessage

AsyncAPIMessage represents a message in the AsyncAPI spec

type AsyncAPIMessageBindings ΒΆ

type AsyncAPIMessageBindings = shared.AsyncAPIMessageBindings

AsyncAPIMessageBindings contains protocol-specific message bindings

type AsyncAPIMessageExample ΒΆ

type AsyncAPIMessageExample = shared.AsyncAPIMessageExample

AsyncAPIMessageExample represents an example of a message

type AsyncAPIMessageReference ΒΆ

type AsyncAPIMessageReference = shared.AsyncAPIMessageReference

AsyncAPIMessageReference references a message

type AsyncAPIMessageTrait ΒΆ

type AsyncAPIMessageTrait = shared.AsyncAPIMessageTrait

AsyncAPIMessageTrait represents reusable message characteristics

type AsyncAPIOAuthFlows ΒΆ

type AsyncAPIOAuthFlows = shared.AsyncAPIOAuthFlows

AsyncAPIOAuthFlows defines OAuth 2.0 flows

type AsyncAPIOperation ΒΆ

type AsyncAPIOperation = shared.AsyncAPIOperation

AsyncAPIOperation represents an operation in the AsyncAPI spec

type AsyncAPIOperationBindings ΒΆ

type AsyncAPIOperationBindings = shared.AsyncAPIOperationBindings

AsyncAPIOperationBindings contains protocol-specific operation bindings

type AsyncAPIOperationReply ΒΆ

type AsyncAPIOperationReply = shared.AsyncAPIOperationReply

AsyncAPIOperationReply represents the reply configuration for an operation

type AsyncAPIOperationReplyAddress ΒΆ

type AsyncAPIOperationReplyAddress = shared.AsyncAPIOperationReplyAddress

AsyncAPIOperationReplyAddress represents the reply address

type AsyncAPIOperationTrait ΒΆ

type AsyncAPIOperationTrait = shared.AsyncAPIOperationTrait

AsyncAPIOperationTrait represents reusable operation characteristics

type AsyncAPIParameter ΒΆ

type AsyncAPIParameter = shared.AsyncAPIParameter

AsyncAPIParameter represents a parameter in channel address

type AsyncAPISecurityRequirement ΒΆ

type AsyncAPISecurityRequirement = shared.AsyncAPISecurityRequirement

AsyncAPISecurityRequirement lists required security schemes

type AsyncAPISecurityScheme ΒΆ

type AsyncAPISecurityScheme = shared.AsyncAPISecurityScheme

AsyncAPISecurityScheme defines a security scheme

type AsyncAPIServer ΒΆ

type AsyncAPIServer = shared.AsyncAPIServer

AsyncAPIServer represents a server in the AsyncAPI spec

type AsyncAPIServerBindings ΒΆ

type AsyncAPIServerBindings = shared.AsyncAPIServerBindings

AsyncAPIServerBindings contains protocol-specific server bindings

type AsyncAPIServerReference ΒΆ

type AsyncAPIServerReference = shared.AsyncAPIServerReference

AsyncAPIServerReference references a server

type AsyncAPISpec ΒΆ

type AsyncAPISpec = shared.AsyncAPISpec

AsyncAPISpec represents the complete AsyncAPI 3.0.0 specification

type AsyncAPITag ΒΆ

type AsyncAPITag = shared.AsyncAPITag

AsyncAPITag represents a tag in the AsyncAPI spec

type BaseExtension ΒΆ

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

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

Example usage:

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

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

func NewBaseExtension ΒΆ

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

NewBaseExtension creates a new base extension with the given identity

func (*BaseExtension) App ΒΆ

func (e *BaseExtension) App() App

App returns the app instance this extension is registered with

func (*BaseExtension) Dependencies ΒΆ

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

Dependencies returns the extension dependencies

func (*BaseExtension) Description ΒΆ

func (e *BaseExtension) Description() string

Description returns the extension description

func (*BaseExtension) Health ΒΆ

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

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

func (*BaseExtension) IsStarted ΒΆ

func (e *BaseExtension) IsStarted() bool

IsStarted returns true if the extension has been started

func (*BaseExtension) LoadConfig ΒΆ

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

LoadConfig loads configuration for this extension from ConfigManager.

It tries the following keys in order:

  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 interface{}) CallbackConfig

NewCompletionCallbackConfig creates a callback config for async operation completion

func NewEventCallbackConfig ΒΆ

func NewEventCallbackConfig(callbackURLExpression string, eventSchema interface{}) CallbackConfig

NewEventCallbackConfig creates a callback config for event notifications

func NewStatusCallbackConfig ΒΆ

func NewStatusCallbackConfig(callbackURLExpression string, statusSchema interface{}) CallbackConfig

NewStatusCallbackConfig creates a callback config for status updates

type CallbackOperation ΒΆ

type CallbackOperation = router.CallbackOperation

CallbackOperation defines an operation that will be called back

func NewCallbackOperation ΒΆ

func NewCallbackOperation(summary, description string) *CallbackOperation

NewCallbackOperation creates a new callback operation

type 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 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 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 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 interface{},
	programmaticConfig interface{},
	defaults interface{},
	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 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 interface{}) 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 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 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 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 License ΒΆ

type License = shared.License

License represents license information

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

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

func WithAcceptedResponse() RouteOption

WithAcceptedResponse creates a 202 Accepted response for async operations

func WithAsyncAPIBinding ΒΆ

func WithAsyncAPIBinding(bindingType string, binding interface{}) RouteOption

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

func WithAsyncAPIChannelDescription ΒΆ

func WithAsyncAPIChannelDescription(description string) RouteOption

WithAsyncAPIChannelDescription sets the channel description

func WithAsyncAPIChannelName ΒΆ

func WithAsyncAPIChannelName(name string) RouteOption

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

func WithAsyncAPIChannelSummary ΒΆ

func WithAsyncAPIChannelSummary(summary string) RouteOption

WithAsyncAPIChannelSummary sets the channel summary

func WithAsyncAPIExternalDocs ΒΆ

func WithAsyncAPIExternalDocs(url, description string) RouteOption

WithAsyncAPIExternalDocs adds external documentation link

func WithAsyncAPIOperationID ΒΆ

func WithAsyncAPIOperationID(id string) RouteOption

WithAsyncAPIOperationID sets a custom operation ID for AsyncAPI

func WithAsyncAPISecurity ΒΆ

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

WithAsyncAPISecurity adds security requirements to the operation

func WithAsyncAPITags ΒΆ

func WithAsyncAPITags(tags ...string) RouteOption

WithAsyncAPITags adds tags to the AsyncAPI operation

func WithAuth ΒΆ

func WithAuth(providerNames ...string) RouteOption

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

Example:

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

func WithAuthAnd ΒΆ

func WithAuthAnd(providerNames ...string) RouteOption

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

Example:

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

func WithBatchResponse ΒΆ

func WithBatchResponse(itemType interface{}, statusCode int) RouteOption

WithBatchResponse creates a response for batch operations

func WithCallback ΒΆ

func WithCallback(config CallbackConfig) RouteOption

WithCallback adds a callback definition to a route

func WithCorrelationID ΒΆ

func WithCorrelationID(location, description string) RouteOption

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

func WithCreatedResponse ΒΆ

func WithCreatedResponse(resourceType interface{}) RouteOption

WithCreatedResponse creates a 201 Created response

func WithDeprecated ΒΆ

func WithDeprecated() RouteOption

func WithDescription ΒΆ

func WithDescription(desc string) RouteOption

func WithDiscriminator ΒΆ

func WithDiscriminator(config DiscriminatorConfig) RouteOption

WithDiscriminator adds discriminator support for polymorphic schemas

func WithErrorResponses ΒΆ

func WithErrorResponses() RouteOption

WithErrorResponses adds standard HTTP error responses to a route

func WithExtension ΒΆ

func WithExtension(name string, ext Extension) RouteOption

func WithExternalDocs ΒΆ

func WithExternalDocs(description, url string) RouteOption

WithExternalDocs adds external documentation link

func WithFileUploadResponse ΒΆ

func WithFileUploadResponse(statusCode int) RouteOption

WithFileUploadResponse creates a response for file upload success

func WithHeaderSchema ΒΆ

func WithHeaderSchema(schemaType interface{}) RouteOption

WithHeaderSchema sets the header parameters schema for OpenAPI generation

func WithListResponse ΒΆ

func WithListResponse(itemType interface{}, statusCode int) RouteOption

WithListResponse creates a simple list response (array of items)

func WithMessageContentType ΒΆ

func WithMessageContentType(contentType string) RouteOption

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

func WithMessageExample ΒΆ

func WithMessageExample(direction, name string, example interface{}) RouteOption

WithMessageExample adds a single message example

func WithMessageExamples ΒΆ

func WithMessageExamples(direction string, examples map[string]interface{}) RouteOption

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

func WithMessageHeaders ΒΆ

func WithMessageHeaders(headersSchema interface{}) RouteOption

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

func WithMetadata ΒΆ

func WithMetadata(key string, value any) RouteOption

func WithMiddleware ΒΆ

func WithMiddleware(mw ...Middleware) RouteOption

func 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 WithOperationID ΒΆ

func WithOperationID(id string) RouteOption

func WithPaginatedResponse ΒΆ

func WithPaginatedResponse(itemType interface{}, statusCode int) RouteOption

WithPaginatedResponse creates a route option for paginated list responses

func WithParameter ΒΆ

func WithParameter(name, in, description string, required bool, example interface{}) RouteOption

WithParameter adds a parameter definition

func WithQuerySchema ΒΆ

func WithQuerySchema(schemaType interface{}) RouteOption

WithQuerySchema sets the query parameters schema for OpenAPI generation

func WithRequestBody ΒΆ

func WithRequestBody(description string, required bool, example interface{}) RouteOption

WithRequestBody adds request body documentation

func WithRequestBodySchema ΒΆ

func WithRequestBodySchema(schemaOrType interface{}) RouteOption

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

func WithRequestContentTypes ΒΆ

func WithRequestContentTypes(types ...string) RouteOption

WithRequestContentTypes specifies the content types for request body

func WithRequestExample ΒΆ

func WithRequestExample(name string, example interface{}) RouteOption

WithRequestExample adds an example for the request body

func WithRequestSchema ΒΆ

func WithRequestSchema(schemaOrType interface{}) RouteOption

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

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

Example:

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

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

func WithRequiredAuth ΒΆ

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

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

Example:

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

func WithResponse ΒΆ

func WithResponse(code int, description string, example interface{}) RouteOption

WithResponse adds a response definition to the route

func WithResponseContentTypes ΒΆ

func WithResponseContentTypes(types ...string) RouteOption

WithResponseContentTypes specifies the content types for response body

func WithResponseExample ΒΆ

func WithResponseExample(statusCode int, name string, example interface{}) RouteOption

WithResponseExample adds an example for a specific response status code

func WithResponseSchema ΒΆ

func WithResponseSchema(statusCode int, description string, schemaOrType interface{}) RouteOption

WithResponseSchema sets a response schema for OpenAPI generation

func WithSSEMessage ΒΆ

func WithSSEMessage(eventName string, schema interface{}) RouteOption

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

func WithSSEMessages ΒΆ

func WithSSEMessages(messageSchemas map[string]interface{}) RouteOption

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

func WithSchemaRef ΒΆ

func WithSchemaRef(name string, schema interface{}) RouteOption

WithSchemaRef adds a schema reference to components

func WithSecurity ΒΆ

func WithSecurity(schemes ...string) RouteOption

WithSecurity sets security requirements for a route

func WithServerProtocol ΒΆ

func WithServerProtocol(serverNames ...string) RouteOption

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

func WithStandardRESTResponses ΒΆ

func WithStandardRESTResponses(resourceType interface{}) RouteOption

WithStandardRESTResponses adds standard REST CRUD responses for a resource

func WithStrictValidation ΒΆ

func WithStrictValidation() RouteOption

WithStrictValidation enables strict validation (validates both request and response)

func WithSummary ΒΆ

func WithSummary(summary string) RouteOption

func WithTags ΒΆ

func WithTags(tags ...string) RouteOption

func WithTimeout ΒΆ

func WithTimeout(d time.Duration) RouteOption

func WithValidation ΒΆ

func WithValidation(enabled bool) RouteOption

WithValidation adds validation middleware to a route

func WithValidationErrorResponse ΒΆ

func WithValidationErrorResponse() RouteOption

WithValidationErrorResponse adds a 422 Unprocessable Entity response for validation errors

func WithWebSocketMessages ΒΆ

func WithWebSocketMessages(sendSchema, receiveSchema interface{}) RouteOption

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

func WithWebhook ΒΆ

func WithWebhook(name string, operation *CallbackOperation) RouteOption

WithWebhook adds a webhook definition to the OpenAPI spec

type Router ΒΆ

type Router = router.Router

Router provides HTTP routing with multiple backend support

func NewRouter ΒΆ

func NewRouter(opts ...RouterOption) Router

NewRouter creates a new router with options

type RouterAdapter ΒΆ

type RouterAdapter = router.RouterAdapter

RouterAdapter wraps a routing backend

func NewBunRouterAdapter ΒΆ

func NewBunRouterAdapter() RouterAdapter

NewBunRouterAdapter creates a BunRouter adapter (default)

type RouterOption ΒΆ

type RouterOption = router.RouterOption

RouterOption configures the router

func 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 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 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
examples
ai-agents-demo command
ai-demo command
cache-demo command
config-example command
database-demo command
events-demo command
mcp-advanced command
mcp-basic command
minimal-app command
observability command
orpc_example command
service-di command
extensions
ai
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.
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.
features module
graphql module
grpc module
kafka module
mqtt module
farp module
internal
di

Jump to

Keyboard shortcuts

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