shared

package
v0.7.4 Latest Latest
Warning

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

Go to latest
Published: Dec 19, 2025 License: Apache-2.0 Imports: 14 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ErrCodeRequired      = "REQUIRED"
	ErrCodeInvalidType   = "INVALID_TYPE"
	ErrCodeInvalidFormat = "INVALID_FORMAT"
	ErrCodeMinLength     = "MIN_LENGTH"
	ErrCodeMaxLength     = "MAX_LENGTH"
	ErrCodeMinValue      = "MIN_VALUE"
	ErrCodeMaxValue      = "MAX_VALUE"
	ErrCodePattern       = "PATTERN"
	ErrCodeEnum          = "ENUM"
	ErrCodeMinItems      = "MIN_ITEMS"
	ErrCodeMaxItems      = "MAX_ITEMS"
	ErrCodeUniqueItems   = "UNIQUE_ITEMS"
)

Common validation error codes.

View Source
const CacheKey = "forge.cache"
View Source
const CacheManagerKey = "forge.cache.manager"
View Source
const CacheServiceKey = "forge.cache.service"
View Source
const CacheWarmer = "forge.cache.warmer"
View Source
const ConfigKey = "forge.config.manager"
View Source
const ContainerKey = "forge.container"
View Source
const DatabaseConnectionKey = "forge.database.connection"
View Source
const DatabaseKey = "forge.database"
View Source
const DatabaseManagerKey = "forge.database.manager"
View Source
const DatabaseRedisClientKey = "forge.database.redis.client"
View Source
const ErrorHandlerKey = "forge.error.handler"
View Source
const EventBusKey = "forge.event.bus"
View Source
const HealthCheckerKey = "forge.health.checker"
View Source
const HealthManagerKey = "forge.health.manager"
View Source
const HealthServiceKey = "forge.health.service"
View Source
const LifecycleManagerKey = "forge.lifecycle.manager"
View Source
const LoggerKey = "forge.logger"
View Source
const MetricsCollectorKey = MetricsKey
View Source
const MetricsKey = "forge.metrics.service"
View Source
const MiddlewareManagerKey = "forge.middleware.manager"
View Source
const PluginManagerKey = "forge.plugin.manager"
View Source
const RouterKey = "forge.router"
View Source
const StreamManagerKey = "forge.stream.manager"
View Source
const StreamingServiceKey = "forge.stream.service"

Variables

View Source
var ContextKeyForSensitiveCleaning = sensitiveCleaningKey{}

ContextKeyForSensitiveCleaning is the key used in request context for sensitive field cleaning. This is exported so it can be used by both the router and context packages.

Functions

func CleanSensitiveFields added in v0.7.0

func CleanSensitiveFields(v any) any

CleanSensitiveFields creates a cleaned copy of the value with sensitive fields processed. It handles nested structs, slices, arrays, and maps recursively.

func ErrContainerError

func ErrContainerError(operation string, cause error) *ferrors.ForgeError

ErrContainerError preserves compatibility for code expecting common.ErrContainerError in v0. There is no direct equivalent code in v2 errors; we map it to a lifecycle error for now.

func ErrContextCancelled

func ErrContextCancelled(operation string) *ferrors.ForgeError

func ErrHealthCheckFailed

func ErrHealthCheckFailed(serviceName string, cause error) *ferrors.ForgeError

func ErrInvalidConfig

func ErrInvalidConfig(configKey string, cause error) *ferrors.ForgeError

func ErrLifecycleError

func ErrLifecycleError(phase string, cause error) *ferrors.ForgeError

func ErrServiceAlreadyExists

func ErrServiceAlreadyExists(serviceName string) *ferrors.ForgeError

func ErrServiceNotFound

func ErrServiceNotFound(serviceName string) *ferrors.ForgeError

func ErrServiceStartFailed

func ErrServiceStartFailed(serviceName string, cause error) *ferrors.ForgeError

func ErrServiceStopFailed

func ErrServiceStopFailed(serviceName string, cause error) *ferrors.ForgeError

ErrServiceStopFailed preserves compatibility; map to lifecycle stop error.

func ErrTimeoutError

func ErrTimeoutError(operation string, timeout time.Duration) *ferrors.ForgeError

func ErrValidationError

func ErrValidationError(field string, cause error) *ferrors.ForgeError

func PrintStartupBanner added in v0.1.13

func PrintStartupBanner(cfg BannerConfig)

PrintStartupBanner prints a styled startup banner to stdout.

func ProcessResponseValue added in v0.7.0

func ProcessResponseValue(v any, headerSetter func(name, value string)) any

ProcessResponseValue is a convenience function that processes a response value with the given header setter callback.

func ProcessResponseValueWithSensitive added in v0.7.0

func ProcessResponseValueWithSensitive(v any, headerSetter func(name, value string), cleanSensitive bool) any

ProcessResponseValueWithSensitive is a convenience function that processes a response value with the given header setter callback and sensitive field cleaning.

Types

type AsyncAPIChannel

type AsyncAPIChannel struct {
	Address      string                        `json:"address,omitempty"` // Channel address (can include params)
	Messages     map[string]*AsyncAPIMessage   `json:"messages,omitempty"`
	Title        string                        `json:"title,omitempty"`
	Summary      string                        `json:"summary,omitempty"`
	Description  string                        `json:"description,omitempty"`
	Servers      []AsyncAPIServerReference     `json:"servers,omitempty"`
	Parameters   map[string]*AsyncAPIParameter `json:"parameters,omitempty"`
	Tags         []AsyncAPITag                 `json:"tags,omitempty"`
	ExternalDocs *ExternalDocs                 `json:"externalDocs,omitempty"`
	Bindings     *AsyncAPIChannelBindings      `json:"bindings,omitempty"`
}

AsyncAPIChannel represents a channel in the AsyncAPI spec.

type AsyncAPIChannelBindings

type AsyncAPIChannelBindings struct {
	WS   *WebSocketChannelBinding `json:"ws,omitempty"`
	HTTP *HTTPChannelBinding      `json:"http,omitempty"`
}

AsyncAPIChannelBindings contains protocol-specific channel bindings.

type AsyncAPIChannelReference

type AsyncAPIChannelReference struct {
	Ref string `json:"$ref" yaml:"$ref"` // #/channels/channelName
}

AsyncAPIChannelReference references a channel.

type AsyncAPIComponents

type AsyncAPIComponents struct {
	Schemas           map[string]*Schema                    `json:"schemas,omitempty"`
	Servers           map[string]*AsyncAPIServer            `json:"servers,omitempty"`
	Channels          map[string]*AsyncAPIChannel           `json:"channels,omitempty"`
	Operations        map[string]*AsyncAPIOperation         `json:"operations,omitempty"`
	Messages          map[string]*AsyncAPIMessage           `json:"messages,omitempty"`
	SecuritySchemes   map[string]*AsyncAPISecurityScheme    `json:"securitySchemes,omitempty"`
	Parameters        map[string]*AsyncAPIParameter         `json:"parameters,omitempty"`
	CorrelationIDs    map[string]*AsyncAPICorrelationID     `json:"correlationIds,omitempty"`
	OperationTraits   map[string]*AsyncAPIOperationTrait    `json:"operationTraits,omitempty"`
	MessageTraits     map[string]*AsyncAPIMessageTrait      `json:"messageTraits,omitempty"`
	ServerBindings    map[string]*AsyncAPIServerBindings    `json:"serverBindings,omitempty"`
	ChannelBindings   map[string]*AsyncAPIChannelBindings   `json:"channelBindings,omitempty"`
	OperationBindings map[string]*AsyncAPIOperationBindings `json:"operationBindings,omitempty"`
	MessageBindings   map[string]*AsyncAPIMessageBindings   `json:"messageBindings,omitempty"`
}

AsyncAPIComponents holds reusable objects for the API spec.

type AsyncAPIConfig

type AsyncAPIConfig struct {
	// Basic info
	Title       string
	Description string
	Version     string

	// AsyncAPI version (default: "3.0.0")
	AsyncAPIVersion string

	// Server configuration
	Servers map[string]*AsyncAPIServer

	// Default content type for messages
	DefaultContentType string // Default: "application/json"

	// External docs, contact, license (reuse OpenAPI types)
	ExternalDocs *ExternalDocs
	Contact      *Contact
	License      *License

	// UI configuration
	UIPath      string // Default: "/asyncapi"
	SpecPath    string // Default: "/asyncapi.json"
	UIEnabled   bool   // Default: true
	SpecEnabled bool   // Default: true

	// Generation options
	PrettyJSON          bool
	IncludeExamples     bool
	IncludeDescriptions bool
}

AsyncAPIConfig configures AsyncAPI 3.0.0 generation.

type AsyncAPICorrelationID

type AsyncAPICorrelationID struct {
	Description string `json:"description,omitempty"`
	Location    string `json:"location"` // Runtime expression like $message.header#/correlationId
}

AsyncAPICorrelationID specifies a correlation ID for request-reply patterns.

type AsyncAPIInfo

type AsyncAPIInfo struct {
	Title          string        `json:"title"`
	Description    string        `json:"description,omitempty"`
	Version        string        `json:"version"`
	TermsOfService string        `json:"termsOfService,omitempty"`
	Contact        *Contact      `json:"contact,omitempty"`
	License        *License      `json:"license,omitempty"`
	Tags           []AsyncAPITag `json:"tags,omitempty"`
	ExternalDocs   *ExternalDocs `json:"externalDocs,omitempty"`
}

AsyncAPIInfo provides metadata about the API.

type AsyncAPIMessage

type AsyncAPIMessage struct {
	MessageID     string                   `json:"messageId,omitempty"`
	Headers       *Schema                  `json:"headers,omitempty"`
	Payload       *Schema                  `json:"payload,omitempty"`
	CorrelationID *AsyncAPICorrelationID   `json:"correlationId,omitempty"`
	ContentType   string                   `json:"contentType,omitempty"`
	Name          string                   `json:"name,omitempty"`
	Title         string                   `json:"title,omitempty"`
	Summary       string                   `json:"summary,omitempty"`
	Description   string                   `json:"description,omitempty"`
	Tags          []AsyncAPITag            `json:"tags,omitempty"`
	ExternalDocs  *ExternalDocs            `json:"externalDocs,omitempty"`
	Bindings      *AsyncAPIMessageBindings `json:"bindings,omitempty"`
	Examples      []AsyncAPIMessageExample `json:"examples,omitempty"`
	Traits        []AsyncAPIMessageTrait   `json:"traits,omitempty"`
}

AsyncAPIMessage represents a message in the AsyncAPI spec.

type AsyncAPIMessageBindings

type AsyncAPIMessageBindings struct {
	WS   *WebSocketMessageBinding `json:"ws,omitempty"`
	HTTP *HTTPMessageBinding      `json:"http,omitempty"`
}

AsyncAPIMessageBindings contains protocol-specific message bindings.

type AsyncAPIMessageExample

type AsyncAPIMessageExample struct {
	Name    string         `json:"name,omitempty"`
	Summary string         `json:"summary,omitempty"`
	Headers map[string]any `json:"headers,omitempty"`
	Payload any            `json:"payload,omitempty"`
}

AsyncAPIMessageExample represents an example of a message.

type AsyncAPIMessageReference

type AsyncAPIMessageReference struct {
	Ref string `json:"$ref" yaml:"$ref"` // #/components/messages/messageName or #/channels/channelName/messages/messageName
}

AsyncAPIMessageReference references a message.

type AsyncAPIMessageTrait

type AsyncAPIMessageTrait struct {
	MessageID     string                   `json:"messageId,omitempty"`
	Headers       *Schema                  `json:"headers,omitempty"`
	CorrelationID *AsyncAPICorrelationID   `json:"correlationId,omitempty"`
	ContentType   string                   `json:"contentType,omitempty"`
	Name          string                   `json:"name,omitempty"`
	Title         string                   `json:"title,omitempty"`
	Summary       string                   `json:"summary,omitempty"`
	Description   string                   `json:"description,omitempty"`
	Tags          []AsyncAPITag            `json:"tags,omitempty"`
	ExternalDocs  *ExternalDocs            `json:"externalDocs,omitempty"`
	Bindings      *AsyncAPIMessageBindings `json:"bindings,omitempty"`
	Examples      []AsyncAPIMessageExample `json:"examples,omitempty"`
}

AsyncAPIMessageTrait represents reusable message characteristics.

type AsyncAPIOAuthFlows

type AsyncAPIOAuthFlows struct {
	Implicit          *OAuthFlow `json:"implicit,omitempty"`
	Password          *OAuthFlow `json:"password,omitempty"`
	ClientCredentials *OAuthFlow `json:"clientCredentials,omitempty"`
	AuthorizationCode *OAuthFlow `json:"authorizationCode,omitempty"`
}

AsyncAPIOAuthFlows defines OAuth 2.0 flows (compatible with OpenAPI OAuthFlows).

type AsyncAPIOperation

type AsyncAPIOperation struct {
	Action       string                        `json:"action"` // send, receive
	Channel      *AsyncAPIChannelReference     `json:"channel"`
	Title        string                        `json:"title,omitempty"`
	Summary      string                        `json:"summary,omitempty"`
	Description  string                        `json:"description,omitempty"`
	Security     []AsyncAPISecurityRequirement `json:"security,omitempty"`
	Tags         []AsyncAPITag                 `json:"tags,omitempty"`
	ExternalDocs *ExternalDocs                 `json:"externalDocs,omitempty"`
	Bindings     *AsyncAPIOperationBindings    `json:"bindings,omitempty"`
	Traits       []AsyncAPIOperationTrait      `json:"traits,omitempty"`
	Messages     []AsyncAPIMessageReference    `json:"messages,omitempty"`
	Reply        *AsyncAPIOperationReply       `json:"reply,omitempty"`
}

AsyncAPIOperation represents an operation in the AsyncAPI spec.

type AsyncAPIOperationBindings

type AsyncAPIOperationBindings struct {
	WS   *WebSocketOperationBinding `json:"ws,omitempty"`
	HTTP *HTTPOperationBinding      `json:"http,omitempty"`
}

AsyncAPIOperationBindings contains protocol-specific operation bindings.

type AsyncAPIOperationReply

type AsyncAPIOperationReply struct {
	Address  *AsyncAPIOperationReplyAddress `json:"address,omitempty"`
	Channel  *AsyncAPIChannelReference      `json:"channel,omitempty"`
	Messages []AsyncAPIMessageReference     `json:"messages,omitempty"`
}

AsyncAPIOperationReply represents the reply configuration for an operation.

type AsyncAPIOperationReplyAddress

type AsyncAPIOperationReplyAddress struct {
	Description string `json:"description,omitempty"`
	Location    string `json:"location,omitempty"` // Runtime expression like $message.header#/replyTo
}

AsyncAPIOperationReplyAddress represents the reply address.

type AsyncAPIOperationTrait

type AsyncAPIOperationTrait struct {
	Title        string                        `json:"title,omitempty"`
	Summary      string                        `json:"summary,omitempty"`
	Description  string                        `json:"description,omitempty"`
	Security     []AsyncAPISecurityRequirement `json:"security,omitempty"`
	Tags         []AsyncAPITag                 `json:"tags,omitempty"`
	ExternalDocs *ExternalDocs                 `json:"externalDocs,omitempty"`
	Bindings     *AsyncAPIOperationBindings    `json:"bindings,omitempty"`
}

AsyncAPIOperationTrait represents reusable operation characteristics.

type AsyncAPIParameter

type AsyncAPIParameter struct {
	Description string   `json:"description,omitempty"`
	Enum        []string `json:"enum,omitempty"`
	Default     string   `json:"default,omitempty"`
	Examples    []string `json:"examples,omitempty"`
	Location    string   `json:"location,omitempty"` // $message.header, $message.payload
	Schema      *Schema  `json:"schema,omitempty"`
}

AsyncAPIParameter represents a parameter in channel address.

type AsyncAPISecurityRequirement

type AsyncAPISecurityRequirement map[string][]string

AsyncAPISecurityRequirement lists required security schemes.

type AsyncAPISecurityScheme

type AsyncAPISecurityScheme struct {
	Type             string              `json:"type"` // userPassword, apiKey, X509, symmetricEncryption, asymmetricEncryption, httpApiKey, http, oauth2, openIdConnect
	Description      string              `json:"description,omitempty"`
	Name             string              `json:"name,omitempty"`             // For apiKey and httpApiKey
	In               string              `json:"in,omitempty"`               // For apiKey and httpApiKey: user, password, query, header, cookie
	Scheme           string              `json:"scheme,omitempty"`           // For http: bearer, basic, etc.
	BearerFormat     string              `json:"bearerFormat,omitempty"`     // For http bearer
	Flows            *AsyncAPIOAuthFlows `json:"flows,omitempty"`            // For oauth2
	OpenIdConnectUrl string              `json:"openIdConnectUrl,omitempty"` // For openIdConnect
	Scopes           []string            `json:"scopes,omitempty"`
}

AsyncAPISecurityScheme defines a security scheme.

type AsyncAPIServer

type AsyncAPIServer struct {
	Host            string                        `json:"host,omitempty"`
	Protocol        string                        `json:"protocol"` // ws, wss, sse, http, https
	ProtocolVersion string                        `json:"protocolVersion,omitempty"`
	Pathname        string                        `json:"pathname,omitempty"`
	Description     string                        `json:"description,omitempty"`
	Title           string                        `json:"title,omitempty"`
	Summary         string                        `json:"summary,omitempty"`
	Variables       map[string]*ServerVariable    `json:"variables,omitempty"`
	Security        []AsyncAPISecurityRequirement `json:"security,omitempty"`
	Tags            []AsyncAPITag                 `json:"tags,omitempty"`
	ExternalDocs    *ExternalDocs                 `json:"externalDocs,omitempty"`
	Bindings        *AsyncAPIServerBindings       `json:"bindings,omitempty"`
}

AsyncAPIServer represents a server in the AsyncAPI spec.

type AsyncAPIServerBindings

type AsyncAPIServerBindings struct {
	WS   *WebSocketServerBinding `json:"ws,omitempty"`
	HTTP *HTTPServerBinding      `json:"http,omitempty"`
}

AsyncAPIServerBindings contains protocol-specific server bindings.

type AsyncAPIServerReference

type AsyncAPIServerReference struct {
	Ref string `json:"$ref" yaml:"$ref"` // #/servers/serverName
}

AsyncAPIServerReference references a server.

type AsyncAPISpec

type AsyncAPISpec struct {
	AsyncAPI   string                        `json:"asyncapi"` // "3.0.0"
	ID         string                        `json:"id,omitempty"`
	Info       AsyncAPIInfo                  `json:"info"`
	Servers    map[string]*AsyncAPIServer    `json:"servers,omitempty"`
	Channels   map[string]*AsyncAPIChannel   `json:"channels"`
	Operations map[string]*AsyncAPIOperation `json:"operations"`
	Components *AsyncAPIComponents           `json:"components,omitempty"`
	Tags       []AsyncAPITag                 `json:"tags,omitempty"`
	Extensions map[string]any                `json:"-"` // x-* extensions
}

AsyncAPISpec represents the complete AsyncAPI 3.0.0 specification.

type AsyncAPITag

type AsyncAPITag struct {
	Name         string        `json:"name"`
	Description  string        `json:"description,omitempty"`
	ExternalDocs *ExternalDocs `json:"externalDocs,omitempty"`
}

AsyncAPITag represents a tag in the AsyncAPI spec.

type BannerConfig added in v0.1.13

type BannerConfig struct {
	AppName     string
	Version     string
	Environment string
	HTTPAddress string
	StartTime   time.Time

	// Optional paths
	OpenAPISpec string
	OpenAPIUI   string
	AsyncAPIUI  string
	HealthPath  string
	MetricsPath string
}

BannerConfig configures the startup banner.

type CollectorStats

type CollectorStats struct {
	Name               string         `json:"name"`
	Started            bool           `json:"started"`
	StartTime          time.Time      `json:"start_time"`
	Uptime             time.Duration  `json:"uptime"`
	MetricsCreated     int64          `json:"metrics_created"`
	MetricsCollected   int64          `json:"metrics_collected"`
	CustomCollectors   int            `json:"custom_collectors"`
	ActiveMetrics      int            `json:"active_metrics"`
	LastCollectionTime time.Time      `json:"last_collection_time"`
	Errors             []string       `json:"errors"`
	ExporterStats      map[string]any `json:"exporter_stats"`
}

CollectorStats contains statistics about the metrics collector.

type Components

type Components struct {
	Schemas         map[string]*Schema        `json:"schemas,omitempty"         yaml:"schemas,omitempty"`
	Responses       map[string]*Response      `json:"responses,omitempty"       yaml:"responses,omitempty"`
	Parameters      map[string]*Parameter     `json:"parameters,omitempty"      yaml:"parameters,omitempty"`
	Examples        map[string]*Example       `json:"examples,omitempty"        yaml:"examples,omitempty"`
	RequestBodies   map[string]*RequestBody   `json:"requestBodies,omitempty"   yaml:"requestBodies,omitempty"`
	Headers         map[string]*Header        `json:"headers,omitempty"         yaml:"headers,omitempty"`
	SecuritySchemes map[string]SecurityScheme `json:"securitySchemes,omitempty" yaml:"securitySchemes,omitempty"`
	Links           map[string]*Link          `json:"links,omitempty"           yaml:"links,omitempty"`
	Callbacks       map[string]any            `json:"callbacks,omitempty"       yaml:"callbacks,omitempty"`
}

Components holds reusable objects for the API spec.

type Configurable

type Configurable interface {
	Configure(config any) error
}

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 Contact

type Contact struct {
	Name  string `json:"name" yaml:"name"`
	Email string `json:"email" yaml:"email"`
	URL   string `json:"url" yaml:"url"`
}

Contact represents contact information.

type Container

type Container interface {
	// Register adds a service factory to the container
	// Returns error if name already registered or factory is invalid
	Register(name string, factory Factory, opts ...RegisterOption) error

	// Resolve returns a service by name
	// Returns error if not found or instantiation fails
	Resolve(name string) (any, error)

	// Has checks if a service is registered
	Has(name string) bool

	// Services returns all registered service names
	Services() []string

	// BeginScope creates a new scope for request-scoped services
	// Scopes must be ended with scope.End() to clean up resources
	BeginScope() Scope

	// Start initializes all services in dependency order
	Start(ctx context.Context) error

	// Stop shuts down all services in reverse order
	Stop(ctx context.Context) error

	// Health checks all services
	Health(ctx context.Context) error

	// Inspect returns diagnostic information about a service
	Inspect(name string) ServiceInfo
}

Container provides dependency injection with lifecycle management.

type Context

type Context interface {

	// Request access
	Request() *http.Request
	Response() http.ResponseWriter

	// Path parameters
	Param(name string) string
	Params() map[string]string

	// Path parameters with type conversion
	ParamInt(name string) (int, error)
	ParamInt64(name string) (int64, error)
	ParamFloat64(name string) (float64, error)
	ParamBool(name string) (bool, error)

	// Path parameters with defaults
	ParamIntDefault(name string, defaultValue int) int
	ParamInt64Default(name string, defaultValue int64) int64
	ParamFloat64Default(name string, defaultValue float64) float64
	ParamBoolDefault(name string, defaultValue bool) bool

	// Query parameters
	Query(name string) string
	QueryDefault(name, defaultValue string) string

	// Request body
	Bind(v any) error
	BindJSON(v any) error
	BindXML(v any) error

	// BindRequest binds and validates request data from all sources (path, query, header, body)
	// using struct tags. Automatically validates based on validation tags.
	BindRequest(v any) error

	// Multipart form data
	FormFile(name string) (multipart.File, *multipart.FileHeader, error)
	FormFiles(name string) ([]*multipart.FileHeader, error)
	FormValue(name string) string
	FormValues(name string) []string
	ParseMultipartForm(maxMemory int64) error

	// Response helpers
	JSON(code int, v any) error
	XML(code int, v any) error
	String(code int, s string) error
	Bytes(code int, data []byte) error
	NoContent(code int) error
	Redirect(code int, url string) error

	// Fluent response builder
	Status(code int) ResponseBuilder

	// SSE streaming helpers
	// WriteSSE writes a Server-Sent Event with automatic content type detection.
	// For string data, sends as-is. For other types, marshals to JSON.
	// Automatically flushes after writing.
	WriteSSE(event string, data any) error

	// Flush flushes any buffered response data to the client.
	// Returns an error if the response writer doesn't support flushing.
	Flush() error

	// Headers
	Header(key string) string
	SetHeader(key, value string)

	// Context values
	Set(key string, value any)
	Get(key string) any
	MustGet(key string) any

	// Request context
	Context() context.Context
	WithContext(ctx context.Context)

	// DI integration
	Container() Container
	Scope() Scope
	Resolve(name string) (any, error)
	Must(name string) any

	// Cookie management
	Cookie(name string) (string, error)
	SetCookie(name, value string, maxAge int)
	SetCookieWithOptions(name, value string, path, domain string, maxAge int, secure, httpOnly bool)
	DeleteCookie(name string)
	HasCookie(name string) bool
	GetAllCookies() map[string]string

	// Session management
	Session() (Session, error)
	SetSession(session Session)
	SaveSession() error
	DestroySession() error
	GetSessionValue(key string) (any, bool)
	SetSessionValue(key string, value any)
	DeleteSessionValue(key string)
	SessionID() string
}

Context wraps http.Request with convenience methods.

type Counter

type Counter interface {
	Inc()
	Add(delta float64)
	Get() float64
	WithLabels(labels map[string]string) Counter
	Reset() error
}

Counter tracks monotonically increasing values.

type CustomCollector

type CustomCollector interface {
	Name() string
	Collect() map[string]any
	// WithLabels(labels map[string]string) CustomCollector
	// Get() map[string]interface{}
	Reset() error
	IsEnabled() bool
}

CustomCollector defines interface for custom metrics collectors.

type DefaultErrorHandler

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

DefaultErrorHandler is the default implementation of ErrorHandler.

func (*DefaultErrorHandler) HandleError

func (h *DefaultErrorHandler) HandleError(ctx context.Context, err error) error

HandleError handles an error and returns it formatted for HTTP response. It checks if the error implements HTTPResponder and uses that for formatting, otherwise falls back to default error formatting.

type Discriminator

type Discriminator struct {
	PropertyName string            `json:"propertyName"`
	Mapping      map[string]string `json:"mapping,omitempty"`
}

Discriminator supports polymorphism.

type Disposable

type Disposable interface {
	Dispose() error
}

Disposable is optional for scoped services that need cleanup.

type Encoding

type Encoding struct {
	ContentType   string             `json:"contentType,omitempty"`
	Headers       map[string]*Header `json:"headers,omitempty"`
	Style         string             `json:"style,omitempty"`
	Explode       bool               `json:"explode,omitempty"`
	AllowReserved bool               `json:"allowReserved,omitempty"`
}

Encoding defines encoding for a property.

type EnumNamer added in v0.7.0

type EnumNamer interface {
	EnumComponentName() string
}

EnumNamer is an optional interface that enum types can implement to provide a custom component name in the OpenAPI schema. If not implemented, the type name will be used as the component name. This is useful for avoiding naming conflicts or providing more descriptive names.

type EnumValuer added in v0.7.0

type EnumValuer interface {
	EnumValues() []any
}

EnumValuer is an optional interface that enum types can implement to provide their possible values for OpenAPI schema generation. This solves Go's limitation where constants cannot be discovered via reflection.

type ErrorHandler

type ErrorHandler interface {
	// HandleError handles an error and returns the formatted error response
	HandleError(ctx context.Context, err error) error
}

ErrorHandler handles errors from HTTP handlers.

func NewDefaultErrorHandler

func NewDefaultErrorHandler(log Logger) ErrorHandler

NewDefaultErrorHandler creates a new default error handler.

type Example

type Example struct {
	Summary       string `json:"summary,omitempty"`
	Description   string `json:"description,omitempty"`
	Value         any    `json:"value,omitempty"`
	ExternalValue string `json:"externalValue,omitempty"`
}

Example provides an example value.

type ExportFormat

type ExportFormat string

ExportFormat represents the format for metrics export.

const (
	ExportFormatPrometheus ExportFormat = "prometheus"
	ExportFormatJSON       ExportFormat = "json"
	ExportFormatInflux     ExportFormat = "influx"
	ExportFormatStatsD     ExportFormat = "statsd"
)

type Exporter

type Exporter interface {
	// Export exports metrics in the specific format
	Export(metrics map[string]any) ([]byte, error)

	// Format returns the export format identifier
	Format() string

	// Stats returns exporter statistics
	Stats() any
}

Exporter defines the interface for metrics export.

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

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

type ExtensionInfo struct {
	Name         string   `json:"name"`
	Version      string   `json:"version"`
	Description  string   `json:"description"`
	Dependencies []string `json:"dependencies"`
	Status       string   `json:"status"` // "registered", "started", "stopped", "error"
}

ExtensionInfo contains information about a registered extension.

type ExternalDocs

type ExternalDocs struct {
	Description string `json:"description" yaml:"description"`
	URL         string `json:"url" yaml:"url"`
}

ExternalDocs points to external documentation.

type Factory

type Factory func(c Container) (any, error)

Factory creates a service instance.

type ForgeError

type ForgeError = ferrors.ForgeError

ForgeError type alias to preserve references via common.ForgeError Allows type assertions like err.(*common.ForgeError).

type Gauge

type Gauge interface {
	Set(value float64)
	Inc()
	Dec()
	Add(delta float64)
	Get() float64
	WithLabels(labels map[string]string) Gauge
	Reset() error
}

Gauge tracks values that can go up or down.

type GroupConfig

type GroupConfig struct {
	Middleware []Middleware
	Tags       []string
	Metadata   map[string]any
}

GroupConfig holds route group configuration.

type GroupOption

type GroupOption interface {
	Apply(*GroupConfig)
}

GroupOption configures a route group.

type HTTPChannelBinding

type HTTPChannelBinding struct {
	Method         string `json:"method,omitempty"` // GET, POST, etc.
	BindingVersion string `json:"bindingVersion,omitempty"`
}

HTTPChannelBinding represents HTTP-specific channel configuration.

type HTTPMessageBinding

type HTTPMessageBinding struct {
	Headers        *Schema `json:"headers,omitempty"`
	StatusCode     int     `json:"statusCode,omitempty"`
	BindingVersion string  `json:"bindingVersion,omitempty"`
}

HTTPMessageBinding represents HTTP-specific message configuration.

type HTTPOperationBinding

type HTTPOperationBinding struct {
	Method         string  `json:"method,omitempty"`
	Query          *Schema `json:"query,omitempty"`
	BindingVersion string  `json:"bindingVersion,omitempty"`
}

HTTPOperationBinding represents HTTP-specific operation configuration.

type HTTPResponder added in v0.5.0

type HTTPResponder interface {
	error

	// StatusCode returns the HTTP status code
	StatusCode() int

	// ResponseBody returns the response body (typically a struct/map for JSON)
	ResponseBody() any
}

HTTPResponder represents an error that knows how to format itself as an HTTP response. This interface provides a unified way to handle errors across the framework, allowing different error types (HTTPError, ValidationErrors, ForgeError) to format themselves consistently for HTTP responses.

type HTTPServerBinding

type HTTPServerBinding struct {
	BindingVersion string `json:"bindingVersion,omitempty"`
}

HTTPServerBinding represents HTTP-specific server configuration.

type Header struct {
	Description string  `json:"description,omitempty"`
	Required    bool    `json:"required,omitempty"`
	Deprecated  bool    `json:"deprecated,omitempty"`
	Schema      *Schema `json:"schema,omitempty"`
	Example     any     `json:"example,omitempty"`
}

Header describes a single header parameter.

type HealthCallback

type HealthCallback func(result *HealthResult)

HealthCallback is a callback function for health status changes.

type HealthCheck

type HealthCheck interface {
	// Name returns the name of the health check implementation.
	Name() string

	// Check performs the health check and returns the result as a HealthResult.
	Check(ctx context.Context) *HealthResult

	// Timeout returns the maximum duration allowed for the health check to complete before timing out.
	Timeout() time.Duration

	// Critical returns true if the health check is considered critical, meaning its failure impacts the overall system health.
	Critical() bool

	// Dependencies returns a slice of strings representing the dependencies for the health check.
	Dependencies() []string
}

HealthCheck defines the interface for health checks.

type HealthCheckFn

type HealthCheckFn func(ctx context.Context) *HealthResult

HealthCheckFn represents a single health check.

type HealthChecker

type HealthChecker interface {
	Health(ctx context.Context) error
}

HealthChecker is optional for services that provide health checks.

type HealthCheckerStats

type HealthCheckerStats struct {
	RegisteredChecks int           `json:"registered_checks"`
	Subscribers      int           `json:"subscribers"`
	Started          bool          `json:"started"`
	Uptime           time.Duration `json:"uptime"`
	LastReportTime   time.Time     `json:"last_report_time"`
	OverallStatus    HealthStatus  `json:"overall_status"`
	LastReport       *HealthReport `json:"last_report,omitempty"`
}

HealthCheckerStats contains statistics about the health checker.

type HealthConfig

type HealthConfig struct {
	Enabled                bool              `json:"enabled"                  yaml:"enabled"`
	CheckInterval          time.Duration     `json:"check_interval"           yaml:"check_interval"`
	ReportInterval         time.Duration     `json:"report_interval"          yaml:"report_interval"`
	EnableAutoDiscovery    bool              `json:"enable_auto_discovery"    yaml:"enable_auto_discovery"`
	EnablePersistence      bool              `json:"enable_persistence"       yaml:"enable_persistence"`
	EnableAlerting         bool              `json:"enable_alerting"          yaml:"enable_alerting"`
	MaxConcurrentChecks    int               `json:"max_concurrent_checks"    yaml:"max_concurrent_checks"`
	DefaultTimeout         time.Duration     `json:"default_timeout"          yaml:"default_timeout"`
	CriticalServices       []string          `json:"critical_services"        yaml:"critical_services"`
	DegradedThreshold      float64           `json:"degraded_threshold"       yaml:"degraded_threshold"`
	UnhealthyThreshold     float64           `json:"unhealthy_threshold"      yaml:"unhealthy_threshold"`
	EnableSmartAggregation bool              `json:"enable_smart_aggregation" yaml:"enable_smart_aggregation"`
	EnablePrediction       bool              `json:"enable_prediction"        yaml:"enable_prediction"`
	EnableEndpoints        bool              `json:"enable_endpoints"         yaml:"enable_endpoints"`
	EndpointPrefix         string            `json:"endpoint_prefix"          yaml:"endpoint_prefix"`
	HistorySize            int               `json:"history_size"             yaml:"history_size"`
	Tags                   map[string]string `json:"tags"                     yaml:"tags"`

	// Service specific configuration
	AutoRegister    bool `json:"auto_register"    yaml:"auto_register"`
	ExposeEndpoints bool `json:"expose_endpoints" yaml:"expose_endpoints"`
	EnableMetrics   bool `json:"enable_metrics"   yaml:"enable_metrics"`

	// Environment information
	Version     string `json:"version"     yaml:"version"`
	Environment string `json:"environment" yaml:"environment"`
}

HealthConfig configures health checks.

func DefaultHealthConfig

func DefaultHealthConfig() HealthConfig

DefaultHealthConfig returns default health configuration.

type HealthManager

type HealthManager interface {
	// Name returns the name or identifier associated with the implementation.
	Name() string

	// Start initializes and starts the health manager, performing necessary setup like auto-registering checks and endpoints.
	Start(ctx context.Context) error

	// Stop gracefully stops the health manager and releases resources. It requires a context for controlled shutdown.
	Stop(ctx context.Context) error

	// OnHealthCheck performs health checks for the service and returns an error if any check fails.
	OnHealthCheck(ctx context.Context) error

	// Register registers a health check. Returns an error if the check name is already registered or invalid.
	Register(check HealthCheck) error

	// RegisterFn registers a function-based health check under a provided name. Returns an error if the name is already registered or invalid.
	RegisterFn(name string, check HealthCheckFn) error

	// Unregister removes a health check associated with the specified name. Returns an error if the operation fails.
	Unregister(name string) error

	// Check executes health checks for all registered services and returns a comprehensive health report.
	Check(ctx context.Context) *HealthReport

	// CheckOne initiates a health check for the specified check by name and returns its health result.
	CheckOne(ctx context.Context, name string) *HealthResult

	// GetStatus returns the current overall health status of the system or service.
	GetStatus() HealthStatus

	// Subscribe registers a callback function that triggers when health status changes.
	Subscribe(callback HealthCallback) error

	// GetLastReport retrieves the most recent health report generated by the health manager.
	GetLastReport() *HealthReport

	// GetChecks retrieves a map of all registered health checks with their corresponding names as keys.
	GetChecks() map[string]HealthCheck

	// GetStats retrieves statistics about the health checker, including registered checks, subscribers, uptime, and overall status.
	GetStats() *HealthCheckerStats

	// SetEnvironment sets the environment name for the health manager.
	SetEnvironment(name string)

	// SetVersion sets the version information for the health manager implementation.
	SetVersion(version string)

	// SetHostname sets the hostname for the health manager instance.
	SetHostname(hostname string)

	// Environment returns the name of the deployment environment as a string.
	Environment() string

	// Hostname returns the hostname of the system or service being monitored.
	Hostname() string

	// Version returns the version information of the health manager as a string.
	Version() string

	// StartTime returns the time when the health manager was initialized or started.
	StartTime() time.Time

	// Reload reloads the health configuration at runtime
	Reload(config *HealthConfig) error
}

HealthManager defines the interface for health checking.

type HealthReport

type HealthReport struct {
	Overall     HealthStatus             `json:"overall"`
	Services    map[string]*HealthResult `json:"services"`
	Timestamp   time.Time                `json:"timestamp"`
	Duration    time.Duration            `json:"duration"`
	Version     string                   `json:"version"`
	Environment string                   `json:"environment"`
	Hostname    string                   `json:"hostname"`
	Uptime      time.Duration            `json:"uptime"`
	Metadata    map[string]any           `json:"metadata,omitempty"`
}

HealthReport represents a comprehensive health report.

func FromJSON

func FromJSON(data []byte) (*HealthReport, error)

FromJSON creates a health report from JSON.

func NewHealthReport

func NewHealthReport() *HealthReport

NewHealthReport creates a new health report.

func (*HealthReport) AddResult

func (hr *HealthReport) AddResult(result *HealthResult)

AddResult adds a health result to the report.

func (*HealthReport) AddResults

func (hr *HealthReport) AddResults(results []*HealthResult)

AddResults adds multiple health results to the report.

func (*HealthReport) GetCriticalCount

func (hr *HealthReport) GetCriticalCount() int

GetCriticalCount returns the number of critical services.

func (*HealthReport) GetCriticalServices

func (hr *HealthReport) GetCriticalServices() []*HealthResult

GetCriticalServices returns all critical services.

func (*HealthReport) GetDegradedCount

func (hr *HealthReport) GetDegradedCount() int

GetDegradedCount returns the number of degraded services.

func (*HealthReport) GetFailedCriticalCount

func (hr *HealthReport) GetFailedCriticalCount() int

GetFailedCriticalCount returns the number of failed critical services.

func (*HealthReport) GetHealthyCount

func (hr *HealthReport) GetHealthyCount() int

GetHealthyCount returns the number of healthy services.

func (*HealthReport) GetServicesByStatus

func (hr *HealthReport) GetServicesByStatus(status HealthStatus) []*HealthResult

GetServicesByStatus returns services filtered by status.

func (*HealthReport) GetUnhealthyCount

func (hr *HealthReport) GetUnhealthyCount() int

GetUnhealthyCount returns the number of unhealthy services.

func (*HealthReport) IsDegraded

func (hr *HealthReport) IsDegraded() bool

IsDegraded returns true if the overall health is degraded.

func (*HealthReport) IsHealthy

func (hr *HealthReport) IsHealthy() bool

IsHealthy returns true if the overall health is healthy.

func (*HealthReport) IsUnhealthy

func (hr *HealthReport) IsUnhealthy() bool

IsUnhealthy returns true if the overall health is unhealthy.

func (*HealthReport) Summary

func (hr *HealthReport) Summary() map[string]any

Summary returns a summary of the health report.

func (*HealthReport) ToJSON

func (hr *HealthReport) ToJSON() ([]byte, error)

ToJSON converts the health report to JSON.

func (*HealthReport) WithDuration

func (hr *HealthReport) WithDuration(duration time.Duration) *HealthReport

WithDuration sets the duration of the health check.

func (*HealthReport) WithEnvironment

func (hr *HealthReport) WithEnvironment(environment string) *HealthReport

WithEnvironment sets the environment information.

func (*HealthReport) WithHostname

func (hr *HealthReport) WithHostname(hostname string) *HealthReport

WithHostname sets the hostname information.

func (*HealthReport) WithMetadata

func (hr *HealthReport) WithMetadata(metadata map[string]any) *HealthReport

WithMetadata adds metadata to the health report.

func (*HealthReport) WithUptime

func (hr *HealthReport) WithUptime(uptime time.Duration) *HealthReport

WithUptime sets the application uptime.

func (*HealthReport) WithVersion

func (hr *HealthReport) WithVersion(version string) *HealthReport

WithVersion sets the version information.

type HealthReportCallback

type HealthReportCallback func(report *HealthReport)

HealthReportCallback is a callback function for health report changes.

type HealthResult

type HealthResult struct {
	Name      string            `json:"name"`
	Status    HealthStatus      `json:"status"`
	Message   string            `json:"message"`
	Details   map[string]any    `json:"details"`
	Timestamp time.Time         `json:"timestamp"`
	Duration  time.Duration     `json:"duration"`
	Error     string            `json:"error,omitempty"`
	Critical  bool              `json:"critical"`
	Tags      map[string]string `json:"tags,omitempty"`
}

HealthResult represents the result of a health check.

func NewHealthResult

func NewHealthResult(name string, status HealthStatus, message string) *HealthResult

NewHealthResult creates a new health result.

func (*HealthResult) IsCritical

func (hr *HealthResult) IsCritical() bool

IsCritical returns true if the health check is critical.

func (*HealthResult) IsDegraded

func (hr *HealthResult) IsDegraded() bool

IsDegraded returns true if the health result is degraded.

func (*HealthResult) IsHealthy

func (hr *HealthResult) IsHealthy() bool

IsHealthy returns true if the health result is healthy.

func (*HealthResult) IsUnhealthy

func (hr *HealthResult) IsUnhealthy() bool

IsUnhealthy returns true if the health result is unhealthy.

func (*HealthResult) String

func (hr *HealthResult) String() string

func (*HealthResult) WithCritical

func (hr *HealthResult) WithCritical(critical bool) *HealthResult

WithCritical marks the health check as critical.

func (*HealthResult) WithDetail

func (hr *HealthResult) WithDetail(key string, value any) *HealthResult

WithDetail adds a single detail to the health result.

func (*HealthResult) WithDetails

func (hr *HealthResult) WithDetails(details map[string]any) *HealthResult

WithDetails adds details to the health result.

func (*HealthResult) WithDuration

func (hr *HealthResult) WithDuration(duration time.Duration) *HealthResult

WithDuration sets the duration of the health check.

func (*HealthResult) WithError

func (hr *HealthResult) WithError(err error) *HealthResult

WithError adds an error to the health result.

func (*HealthResult) WithMessage

func (hr *HealthResult) WithMessage(message string) *HealthResult

func (*HealthResult) WithStatus

func (hr *HealthResult) WithStatus(status HealthStatus) *HealthResult

func (*HealthResult) WithTag

func (hr *HealthResult) WithTag(key, value string) *HealthResult

WithTag adds a single tag to the health result.

func (*HealthResult) WithTags

func (hr *HealthResult) WithTags(tags map[string]string) *HealthResult

WithTags adds tags to the health result.

func (*HealthResult) WithTimestamp

func (hr *HealthResult) WithTimestamp(timestamp time.Time) *HealthResult

func (*HealthResult) WithTimestampNow

func (hr *HealthResult) WithTimestampNow() *HealthResult

type HealthStatus

type HealthStatus string

HealthStatus represents the health status of a service or component.

const (
	HealthStatusHealthy   HealthStatus = "healthy"
	HealthStatusDegraded  HealthStatus = "degraded"
	HealthStatusUnhealthy HealthStatus = "unhealthy"
	HealthStatusUnknown   HealthStatus = "unknown"
)

func (HealthStatus) IsDegraded

func (hs HealthStatus) IsDegraded() bool

IsDegraded returns true if the status is degraded.

func (HealthStatus) IsHealthy

func (hs HealthStatus) IsHealthy() bool

IsHealthy returns true if the status is healthy.

func (HealthStatus) IsUnhealthy

func (hs HealthStatus) IsUnhealthy() bool

IsUnhealthy returns true if the status is unhealthy.

func (HealthStatus) IsUnknown

func (hs HealthStatus) IsUnknown() bool

IsUnknown returns true if the status is unknown.

func (HealthStatus) Severity

func (hs HealthStatus) Severity() int

Severity returns a numeric severity level for comparison.

func (HealthStatus) String

func (hs HealthStatus) String() string

String returns the string representation of the health status.

type Histogram

type Histogram interface {
	Observe(value float64)
	ObserveDuration(start time.Time)
	GetBuckets() map[float64]uint64
	GetCount() uint64
	GetSum() float64
	GetMean() float64
	GetPercentile(percentile float64) float64
	WithLabels(labels map[string]string) Histogram
	Reset() error
}

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 struct {
	Title          string   `json:"title"`
	Description    string   `json:"description,omitempty"`
	Version        string   `json:"version"`
	TermsOfService string   `json:"termsOfService,omitempty"`
	Contact        *Contact `json:"contact,omitempty"`
	License        *License `json:"license,omitempty"`
}

Info provides metadata about the API.

type License

type License struct {
	Name string `json:"name" yaml:"name"`
	URL  string `json:"url" yaml:"url"`
}

License represents license information.

type Link struct {
	OperationRef string         `json:"operationRef,omitempty"`
	OperationID  string         `json:"operationId,omitempty"`
	Parameters   map[string]any `json:"parameters,omitempty"`
	RequestBody  any            `json:"requestBody,omitempty"`
	Description  string         `json:"description,omitempty"`
	Server       *OpenAPIServer `json:"server,omitempty"`
}

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

type Logger

type Logger = logger.Logger

Logger is an alias to the centralized logger interface in v2/internal/logger. This preserves backward compatibility for components that used common.Logger.

type MediaType

type MediaType struct {
	Schema   *Schema              `json:"schema,omitempty"`
	Example  any                  `json:"example,omitempty"`
	Examples map[string]*Example  `json:"examples,omitempty"`
	Encoding map[string]*Encoding `json:"encoding,omitempty"`
}

MediaType provides schema and examples for a media type.

type MetricType

type MetricType string

MetricType represents the type of metric.

const (
	MetricTypeCounter   MetricType = "counter"
	MetricTypeGauge     MetricType = "gauge"
	MetricTypeHistogram MetricType = "histogram"
	MetricTypeTimer     MetricType = "timer"
)

type Metrics

type Metrics interface {
	Service
	HealthChecker

	// Counter metrics (monotonically increasing)
	// Labels should be provided as key-value pairs: "key1", "value1", "key2", "value2"
	Counter(name string, labels ...string) Counter

	// Gauge metrics (can go up or down)
	// Labels should be provided as key-value pairs: "key1", "value1", "key2", "value2"
	Gauge(name string, labels ...string) Gauge

	// Histogram metrics (distributions)
	// Labels should be provided as key-value pairs: "key1", "value1", "key2", "value2"
	Histogram(name string, labels ...string) Histogram

	// Timer metrics (time taken to complete an operation)
	// Labels should be provided as key-value pairs: "key1", "value1", "key2", "value2"
	Timer(name string, labels ...string) Timer

	// Export metrics (Prometheus format by default)
	Export(format ExportFormat) ([]byte, error)

	// Export to file
	ExportToFile(format ExportFormat, filename string) error

	// Register a custom collector
	RegisterCollector(collector CustomCollector) error

	// Unregister a custom collector
	UnregisterCollector(name string) error

	// Get all custom collectors
	GetCollectors() []CustomCollector

	// Reset metrics
	Reset() error

	// Reset metric
	ResetMetric(name string) error

	// Get metrics
	GetMetrics() map[string]any

	// Get metrics by type
	GetMetricsByType(metricType MetricType) map[string]any

	// Get metrics by tag
	GetMetricsByTag(tagKey, tagValue string) map[string]any

	// Get stats
	GetStats() CollectorStats

	// Reload reloads the metrics configuration at runtime
	Reload(config *MetricsConfig) error
}

Metrics provides telemetry collection.

type MetricsConfig

type MetricsConfig struct {
	Enabled     bool
	MetricsPath string
	Namespace   string

	EnableSystemMetrics  bool                                             `json:"enable_system_metrics"  yaml:"enable_system_metrics"`
	EnableRuntimeMetrics bool                                             `json:"enable_runtime_metrics" yaml:"enable_runtime_metrics"`
	EnableHTTPMetrics    bool                                             `json:"enable_http_metrics"    yaml:"enable_http_metrics"`
	CollectionInterval   time.Duration                                    `json:"collection_interval"    yaml:"collection_interval"`
	StorageConfig        *MetricsStorageConfig[map[string]any]            `json:"storage"                yaml:"storage"`
	Exporters            map[string]MetricsExporterConfig[map[string]any] `json:"exporters"              yaml:"exporters"`
	DefaultTags          map[string]string                                `json:"default_tags"           yaml:"default_tags"`
	MaxMetrics           int                                              `json:"max_metrics"            yaml:"max_metrics"`
	BufferSize           int                                              `json:"buffer_size"            yaml:"buffer_size"`
}

MetricsConfig configures metrics collection.

type MetricsExporterConfig

type MetricsExporterConfig[T any] struct {
	Enabled  bool          `json:"enabled"  yaml:"enabled"`
	Interval time.Duration `json:"interval" yaml:"interval"`
	Config   T             `json:"config"   yaml:"config"`
}

ExporterConfig contains configuration for exporters.

type MetricsStorageConfig

type MetricsStorageConfig[T any] struct {
	Type   string `json:"type"   yaml:"type"`
	Config T      `json:"config" yaml:"config"`
}

StorageConfig contains storage configuration.

type Middleware

type Middleware func(http.Handler) http.Handler

Middleware wraps HTTP handlers.

type OAuthFlow

type OAuthFlow struct {
	AuthorizationURL string            `json:"authorizationUrl" yaml:"authorizationUrl"`
	TokenURL         string            `json:"tokenUrl" yaml:"tokenUrl"`
	RefreshURL       string            `json:"refreshUrl" yaml:"refreshUrl"`
	Scopes           map[string]string `json:"scopes,omitempty" yaml:"scopes,omitempty"`
}

OAuthFlow defines a single OAuth 2.0 flow.

type OAuthFlows

type OAuthFlows struct {
	Implicit          *OAuthFlow
	Password          *OAuthFlow
	ClientCredentials *OAuthFlow
	AuthorizationCode *OAuthFlow
}

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 struct {
	// Basic info
	Title       string `json:"title" yaml:"title"`
	Description string `json:"description" yaml:"description"`
	Version     string `json:"version" yaml:"version"`

	// OpenAPI version (default: "3.1.0")
	OpenAPIVersion string `json:"openAPIVersion" yaml:"openAPIVersion"`

	// Server configuration
	Servers []OpenAPIServer `json:"servers" yaml:"servers"`

	// Security schemes
	Security map[string]SecurityScheme `json:"security" yaml:"security"`

	// Global tags
	Tags []OpenAPITag `json:"tags" yaml:"tags"`

	// External docs
	ExternalDocs *ExternalDocs `json:"externalDocs" yaml:"externalDocs"`

	// Contact info
	Contact *Contact `json:"contact" yaml:"contact"`
	License *License `json:"license" yaml:"license"`

	// UI configuration
	UIPath      string `json:"uiPath" yaml:"uiPath"`           // Default: "/swagger"
	SpecPath    string `json:"specPath" yaml:"specPath"`       // Default: "/openapi.json"
	UIEnabled   bool   `json:"uiEnabled" yaml:"uiEnabled"`     // Default: true
	SpecEnabled bool   `json:"specEnabled" yaml:"specEnabled"` // Default: true

	// Generation options
	PrettyJSON          bool `json:"prettyJSON" yaml:"prettyJSON"`
	IncludeExamples     bool `json:"includeExamples" yaml:"includeExamples"`
	IncludeDescriptions bool `json:"includeDescriptions" yaml:"includeDescriptions"`
	ValidateResponses   bool `json:"validateResponses" yaml:"validateResponses"`
}

OpenAPIConfig configures OpenAPI 3.1.0 generation.

type OpenAPIServer

type OpenAPIServer struct {
	URL         string                    `json:"url" yaml:"url"`
	Description string                    `json:"description,omitempty" yaml:"description,omitempty"`
	Title       string                    `json:"title,omitempty" yaml:"title,omitempty"`
	Variables   map[string]ServerVariable `json:"variables,omitempty" yaml:"variables,omitempty"`
}

OpenAPIServer represents a server in the OpenAPI spec.

type OpenAPISpec

type OpenAPISpec struct {
	OpenAPI      string                `json:"openapi"`
	Info         Info                  `json:"info"`
	Servers      []OpenAPIServer       `json:"servers,omitempty"`
	Paths        map[string]*PathItem  `json:"paths"`
	Components   *Components           `json:"components,omitempty"`
	Security     []SecurityRequirement `json:"security,omitempty"`
	Tags         []OpenAPITag          `json:"tags,omitempty"`
	ExternalDocs *ExternalDocs         `json:"externalDocs,omitempty"`
	Webhooks     map[string]*PathItem  `json:"webhooks,omitempty"`
}

OpenAPISpec represents the complete OpenAPI 3.1.0 specification.

type OpenAPITag

type OpenAPITag struct {
	Name         string        `json:"name" yaml:"name"`
	Description  string        `json:"description" yaml:"description"`
	ExternalDocs *ExternalDocs `json:"externalDocs,omitempty" yaml:"externalDocs,omitempty"`
}

OpenAPITag represents a tag in the OpenAPI spec.

type Operation

type Operation struct {
	Tags         []string                        `json:"tags,omitempty"         yaml:"tags,omitempty"`
	Summary      string                          `json:"summary,omitempty"      yaml:"summary,omitempty"`
	Description  string                          `json:"description,omitempty"  yaml:"description,omitempty"`
	OperationID  string                          `json:"operationId,omitempty"  yaml:"operationId,omitempty"`
	Parameters   []Parameter                     `json:"parameters,omitempty"   yaml:"parameters,omitempty"`
	RequestBody  *RequestBody                    `json:"requestBody,omitempty"  yaml:"requestBody,omitempty"`
	Responses    map[string]*Response            `json:"responses"              yaml:"responses"`
	Callbacks    map[string]map[string]*PathItem `json:"callbacks,omitempty"    yaml:"callbacks,omitempty"`
	Deprecated   bool                            `json:"deprecated,omitempty"   yaml:"deprecated,omitempty"`
	Security     []SecurityRequirement           `json:"security,omitempty"     yaml:"security,omitempty"`
	ExternalDocs *ExternalDocs                   `json:"externalDocs,omitempty" yaml:"externalDocs,omitempty"`
}

Operation describes a single API operation on a path.

type Parameter

type Parameter struct {
	Name            string              `json:"name"                      yaml:"name"`
	In              string              `json:"in"                        yaml:"in"` // "query", "header", "path", "cookie"
	Description     string              `json:"description,omitempty"     yaml:"description,omitempty"`
	Required        bool                `json:"required,omitempty"        yaml:"required,omitempty"`
	Deprecated      bool                `json:"deprecated,omitempty"      yaml:"deprecated,omitempty"`
	AllowEmptyValue bool                `json:"allowEmptyValue,omitempty" yaml:"allowEmptyValue,omitempty"`
	Schema          *Schema             `json:"schema,omitempty"          yaml:"schema,omitempty"`
	Example         any                 `json:"example,omitempty"         yaml:"example,omitempty"`
	Examples        map[string]*Example `json:"examples,omitempty"        yaml:"examples,omitempty"`
}

Parameter describes a single operation parameter.

type PathItem

type PathItem struct {
	Summary     string      `json:"summary,omitempty"`
	Description string      `json:"description,omitempty"`
	Get         *Operation  `json:"get,omitempty"`
	Put         *Operation  `json:"put,omitempty"`
	Post        *Operation  `json:"post,omitempty"`
	Delete      *Operation  `json:"delete,omitempty"`
	Options     *Operation  `json:"options,omitempty"`
	Head        *Operation  `json:"head,omitempty"`
	Patch       *Operation  `json:"patch,omitempty"`
	Parameters  []Parameter `json:"parameters,omitempty"`
}

PathItem describes operations available on a single path.

type RegisterOption

type RegisterOption struct {
	Lifecycle    string // "singleton", "scoped", or "transient"
	Dependencies []string
	Metadata     map[string]string
	Groups       []string
}

RegisterOption is a configuration option for service registration.

func MergeOptions

func MergeOptions(opts []RegisterOption) RegisterOption

MergeOptions combines multiple options.

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 struct {
	Description string                `json:"description,omitempty"`
	Content     map[string]*MediaType `json:"content"`
	Required    bool                  `json:"required,omitempty"`
}

RequestBody describes a single request body.

type Response

type Response struct {
	Description string                `json:"description"`
	Headers     map[string]*Header    `json:"headers,omitempty"`
	Content     map[string]*MediaType `json:"content,omitempty"`
	Links       map[string]*Link      `json:"links,omitempty"`
}

Response describes a single response from an API operation.

type ResponseBuilder

type ResponseBuilder interface {
	JSON(v any) error
	XML(v any) error
	String(s string) error
	Bytes(data []byte) error
	NoContent() error
	Header(key, value string) ResponseBuilder
}

ResponseBuilder provides fluent response building.

type ResponseProcessor added in v0.7.0

type ResponseProcessor struct {
	// HeaderSetter is called for each header:"..." tagged field with non-zero value.
	HeaderSetter func(name, value string)
	// CleanSensitive when true, processes sensitive fields.
	CleanSensitive bool
}

ResponseProcessor handles response struct processing. It extracts headers and unwraps body fields based on struct tags.

func (*ResponseProcessor) ProcessResponse added in v0.7.0

func (p *ResponseProcessor) ProcessResponse(v any) any

ProcessResponse handles response struct tags: - Calls HeaderSetter for header:"..." fields with non-zero values - Returns the unwrapped body if a body:"" tag is found - Cleans sensitive fields if CleanSensitive is true - Falls back to original value if no special tags found.

type RouteConfig

type RouteConfig struct {
	Name        string
	Summary     string
	Description string
	Tags        []string
	Middleware  []Middleware
	Timeout     time.Duration
	Metadata    map[string]any
	Extensions  map[string]Extension

	// OpenAPI metadata
	OperationID string
	Deprecated  bool
}

RouteConfig holds route configuration.

type RouteExtension

type RouteExtension interface {
	Name() string
	Validate() error
}

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 struct {
	Name        string
	Method      string
	Path        string
	Pattern     string
	Handler     any
	Middleware  []Middleware
	Tags        []string
	Metadata    map[string]any
	Extensions  map[string]Extension
	Summary     string
	Description string
}

RouteInfo provides route information for inspection.

type RouteOption

type RouteOption interface {
	Apply(*RouteConfig)
}

RouteOption configures a route.

type Router

type Router interface {
	// HTTP Methods - register routes
	GET(path string, handler any, opts ...RouteOption) error
	POST(path string, handler any, opts ...RouteOption) error
	PUT(path string, handler any, opts ...RouteOption) error
	DELETE(path string, handler any, opts ...RouteOption) error
	PATCH(path string, handler any, opts ...RouteOption) error
	OPTIONS(path string, handler any, opts ...RouteOption) error
	HEAD(path string, handler any, opts ...RouteOption) error

	// Grouping - organize routes
	Group(prefix string, opts ...GroupOption) Router

	// Middleware - wrap handlers
	Use(middleware ...Middleware)

	// Lifecycle
	Start(ctx context.Context) error
	Stop(ctx context.Context) error

	// HTTP serving
	ServeHTTP(w http.ResponseWriter, r *http.Request)
	Handler() http.Handler

	// Inspection
	Routes() []RouteInfo
	RouteByName(name string) (RouteInfo, bool)
	RoutesByTag(tag string) []RouteInfo
	RoutesByMetadata(key string, value any) []RouteInfo
}

Router provides HTTP routing with multiple backend support.

type RouterAdapter

type RouterAdapter interface {
	// Handle registers a route
	Handle(method, path string, handler http.Handler)

	// Mount registers a sub-handler
	Mount(path string, handler http.Handler)

	// UseGlobal registers global middleware that runs before routing
	// This is critical for CORS preflight handling - middleware added here
	// will run even for routes that don't have explicit handlers (e.g., OPTIONS requests)
	UseGlobal(middleware func(http.Handler) http.Handler)

	// ServeHTTP dispatches requests
	ServeHTTP(w http.ResponseWriter, r *http.Request)

	// Close cleans up resources
	Close() error
}

RouterAdapter wraps a routing backend.

type RouterOption

type RouterOption interface {
	Apply(*routerConfig)
}

RouterOption configures the router.

type Schema

type Schema struct {
	Type        string `json:"type,omitempty"`
	Format      string `json:"format,omitempty"`
	Title       string `json:"title,omitempty"`
	Description string `json:"description,omitempty"`
	Default     any    `json:"default,omitempty"`
	Nullable    bool   `json:"nullable,omitempty"`
	ReadOnly    bool   `json:"readOnly,omitempty"`
	WriteOnly   bool   `json:"writeOnly,omitempty"`
	Example     any    `json:"example,omitempty"`
	Deprecated  bool   `json:"deprecated,omitempty"`

	// Validation
	MultipleOf       float64  `json:"multipleOf,omitempty"`
	Maximum          float64  `json:"maximum,omitempty"`
	ExclusiveMaximum bool     `json:"exclusiveMaximum,omitempty"`
	Minimum          float64  `json:"minimum,omitempty"`
	ExclusiveMinimum bool     `json:"exclusiveMinimum,omitempty"`
	MaxLength        int      `json:"maxLength,omitempty"`
	MinLength        int      `json:"minLength,omitempty"`
	Pattern          string   `json:"pattern,omitempty"`
	MaxItems         int      `json:"maxItems,omitempty"`
	MinItems         int      `json:"minItems,omitempty"`
	UniqueItems      bool     `json:"uniqueItems,omitempty"`
	MaxProperties    int      `json:"maxProperties,omitempty"`
	MinProperties    int      `json:"minProperties,omitempty"`
	Required         []string `json:"required,omitempty"`
	Enum             []any    `json:"enum,omitempty"`

	// Object/Array properties
	Properties           map[string]*Schema `json:"properties,omitempty"`
	AdditionalProperties any                `json:"additionalProperties,omitempty"`
	Items                *Schema            `json:"items,omitempty"`

	// Composition
	AllOf []Schema `json:"allOf,omitempty"`
	AnyOf []Schema `json:"anyOf,omitempty"`
	OneOf []Schema `json:"oneOf,omitempty"`
	Not   *Schema  `json:"not,omitempty"`

	// Discriminator (OpenAPI 3.1.0)
	Discriminator *Discriminator `json:"discriminator,omitempty"`

	// Reference
	Ref string `json:"$ref,omitempty"`
}

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

type Scope

type Scope interface {
	// Resolve returns a service by name from this scope
	// Scoped services are cached within the scope
	// Singleton services are resolved from parent container
	Resolve(name string) (any, error)

	// End cleans up all scoped services in this scope
	// Must be called when scope is no longer needed (typically in defer)
	End() error
}

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

type SecurityRequirement

type SecurityRequirement map[string][]string

SecurityRequirement lists required security schemes.

type SecurityScheme

type SecurityScheme struct {
	Type             string      `json:"type"                       yaml:"type"` // "apiKey", "http", "oauth2", "openIdConnect"
	Description      string      `json:"description,omitempty"      yaml:"description,omitempty"`
	Name             string      `json:"name,omitempty"             yaml:"name,omitempty"`         // For apiKey
	In               string      `json:"in,omitempty"               yaml:"in,omitempty"`           // For apiKey: "query", "header", "cookie"
	Scheme           string      `json:"scheme,omitempty"           yaml:"scheme,omitempty"`       // For http: "bearer", "basic"
	BearerFormat     string      `json:"bearerFormat,omitempty"     yaml:"bearerFormat,omitempty"` // For http bearer
	Flows            *OAuthFlows `json:"flows,omitempty"            yaml:"flows,omitempty"`
	OpenIdConnectUrl string      `json:"openIdConnectUrl,omitempty" yaml:"openIdConnectUrl,omitempty"`
}

SecurityScheme defines a security scheme.

type SensitiveFieldConfig added in v0.7.0

type SensitiveFieldConfig struct {
	Mode SensitiveMode
	Mask string // Custom mask for SensitiveModeMask
}

SensitiveFieldConfig holds configuration for a sensitive field.

func ParseSensitiveTag added in v0.7.0

func ParseSensitiveTag(tagValue string) *SensitiveFieldConfig

ParseSensitiveTag parses the sensitive tag value and returns the configuration. Supported formats:

  • sensitive:"true" -> zero value
  • sensitive:"redact" -> "[REDACTED]"
  • sensitive:"mask:***" -> custom mask "***"

type SensitiveMode added in v0.7.0

type SensitiveMode int

SensitiveMode specifies how sensitive fields should be cleaned.

const (
	// SensitiveModeZero sets sensitive fields to their zero value.
	SensitiveModeZero SensitiveMode = iota
	// SensitiveModeRedact replaces sensitive fields with "[REDACTED]".
	SensitiveModeRedact
	// SensitiveModeMask replaces sensitive fields with a custom mask.
	SensitiveModeMask
)

type ServerVariable

type ServerVariable struct {
	Default     string   `json:"default" yaml:"default"`
	Enum        []string `json:"enum" yaml:"enum"`
	Description string   `json:"description" yaml:"description"`
}

ServerVariable represents a variable in a server URL.

type Service

type Service interface {
	Name() string
	Start(ctx context.Context) error
	Stop(ctx context.Context) error
}

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

type ServiceInfo

type ServiceInfo struct {
	Name         string
	Type         string
	Lifecycle    string
	Dependencies []string
	Started      bool
	Healthy      bool
	Metadata     map[string]string
}

ServiceInfo contains diagnostic information.

type Session added in v0.4.0

type Session interface {
	GetID() string
	GetUserID() string
	GetData(key string) (any, bool)
	SetData(key string, value any)
	DeleteData(key string)
	IsExpired() bool
	IsValid() bool
	Touch()
	GetCreatedAt() time.Time
	GetExpiresAt() time.Time
	GetLastAccessedAt() time.Time
}

Session represents a user session (mirrors security.Session).

type Timer

type Timer interface {
	Record(duration time.Duration)
	Time() func()
	GetCount() uint64
	GetMean() time.Duration
	GetPercentile(percentile float64) time.Duration
	GetMin() time.Duration
	GetMax() time.Duration
	Get() time.Duration
	Reset()
}

Timer represents a timer metric.

type ValidationError added in v0.5.0

type ValidationError struct {
	Field   string `json:"field"`
	Message string `json:"message"`
	Value   any    `json:"value,omitempty"`
	Code    string `json:"code,omitempty"`
}

ValidationError represents a single field validation error.

type ValidationErrorResponse added in v0.5.0

type ValidationErrorResponse struct {
	Error            string            `json:"error"`
	Code             int               `json:"code"`
	ValidationErrors []ValidationError `json:"validationErrors"`
}

ValidationErrorResponse is the HTTP response for validation errors.

func NewValidationErrorResponse added in v0.5.0

func NewValidationErrorResponse(errors *ValidationErrors) *ValidationErrorResponse

NewValidationErrorResponse creates a new validation error response.

type ValidationErrors added in v0.5.0

type ValidationErrors struct {
	Errors []ValidationError `json:"errors"`
}

ValidationErrors is a collection of validation errors.

func NewValidationErrors added in v0.5.0

func NewValidationErrors() *ValidationErrors

NewValidationErrors creates a new ValidationErrors instance.

func (*ValidationErrors) Add added in v0.5.0

func (ve *ValidationErrors) Add(field, message string, value any)

Add adds a validation error.

func (*ValidationErrors) AddWithCode added in v0.5.0

func (ve *ValidationErrors) AddWithCode(field, message, code string, value any)

AddWithCode adds a validation error with a code.

func (*ValidationErrors) Count added in v0.5.0

func (ve *ValidationErrors) Count() int

Count returns the number of validation errors.

func (*ValidationErrors) Error added in v0.5.0

func (ve *ValidationErrors) Error() string

Error implements the error interface.

func (*ValidationErrors) HasErrors added in v0.5.0

func (ve *ValidationErrors) HasErrors() bool

HasErrors returns true if there are validation errors.

func (*ValidationErrors) ResponseBody added in v0.5.0

func (ve *ValidationErrors) ResponseBody() any

ResponseBody returns the response body (implements HTTPResponder)

func (*ValidationErrors) StatusCode added in v0.5.0

func (ve *ValidationErrors) StatusCode() int

StatusCode returns 422 for validation errors (implements HTTPResponder)

func (*ValidationErrors) ToJSON added in v0.5.0

func (ve *ValidationErrors) ToJSON() ([]byte, error)

ToJSON converts validation errors to JSON bytes.

type WebSocketChannelBinding

type WebSocketChannelBinding struct {
	Method         string  `json:"method,omitempty"` // GET, POST
	Query          *Schema `json:"query,omitempty"`
	Headers        *Schema `json:"headers,omitempty"`
	BindingVersion string  `json:"bindingVersion,omitempty"`
}

WebSocketChannelBinding represents WebSocket-specific channel configuration.

type WebSocketMessageBinding

type WebSocketMessageBinding struct {
	BindingVersion string `json:"bindingVersion,omitempty"`
}

WebSocketMessageBinding represents WebSocket-specific message configuration.

type WebSocketOperationBinding

type WebSocketOperationBinding struct {
	BindingVersion string `json:"bindingVersion,omitempty"`
}

WebSocketOperationBinding represents WebSocket-specific operation configuration.

type WebSocketServerBinding

type WebSocketServerBinding struct {
	Headers        *Schema `json:"headers,omitempty"`
	Query          *Schema `json:"query,omitempty"`
	BindingVersion string  `json:"bindingVersion,omitempty"`
}

WebSocketServerBinding represents WebSocket-specific server configuration.

Jump to

Keyboard shortcuts

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