shared

package
v0.9.2 Latest Latest
Warning

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

Go to latest
Published: Feb 10, 2026 License: Apache-2.0 Imports: 15 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 DepNames added in v0.8.0

func DepNames(deps []Dep) []string

DepNames extracts just the names from a slice of Dep specs. Useful for backward compatibility with code expecting []string.

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 = metrics.CollectorStats

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 = di.Container

Container provides dependency injection with lifecycle management.

type Context

type Context = http.Context

Context wraps http.Request with convenience methods.

type Counter

type Counter = metrics.Counter

Counter tracks monotonically increasing values.

type CustomCollector

type CustomCollector = metrics.CustomCollector

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 Dep added in v0.8.0

type Dep = di.Dep

Dep represents a dependency specification for a service. It describes what service is needed, what type it should be, and how it should be resolved (eager, lazy, optional).

func DepsFromNames added in v0.8.0

func DepsFromNames(names []string) []Dep

DepsFromNames converts a slice of names to eager Dep specs. Useful for backward compatibility with old []string dependencies.

func Eager added in v0.8.0

func Eager(name string) Dep

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

func EagerTyped added in v0.8.0

func EagerTyped[T any](name string) Dep

EagerTyped creates an eager dependency with type information.

func Lazy added in v0.8.0

func Lazy(name string) Dep

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

func LazyOptional added in v0.8.0

func LazyOptional(name string) Dep

LazyOptional creates a lazy optional dependency specification. The dependency is resolved on first access and returns nil if not found.

func LazyOptionalTyped added in v0.8.0

func LazyOptionalTyped[T any](name string) Dep

LazyOptionalTyped creates a lazy optional dependency with type information.

func LazyTyped added in v0.8.0

func LazyTyped[T any](name string) Dep

LazyTyped creates a lazy dependency with type information.

func Optional added in v0.8.0

func Optional(name string) Dep

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

func OptionalTyped added in v0.8.0

func OptionalTyped[T any](name string) Dep

OptionalTyped creates an optional dependency with type information.

type DepMode added in v0.8.0

type DepMode = di.DepMode

DepMode specifies how a dependency should be resolved.

const (
	// DepEager resolves the dependency immediately during service creation.
	// Fails if the dependency is not found.
	DepEager DepMode = di.DepEager

	// DepLazy defers resolution until the dependency is first accessed.
	// Useful for breaking circular dependencies or expensive services.
	DepLazy DepMode = di.DepLazy

	// DepOptional resolves immediately but returns nil if not found.
	// Does not fail if the dependency is missing.
	DepOptional DepMode = di.DepOptional

	// DepLazyOptional combines lazy resolution with optional behavior.
	// Defers resolution and returns nil if not found on access.
	DepLazyOptional DepMode = di.DepLazyOptional
)

type DependencyProvider added in v0.8.0

type DependencyProvider interface {
	// Dependencies returns the list of dependencies this service requires.
	Dependencies() []Dep
}

DependencyProvider is implemented by services that declare their dependencies. The container will auto-discover and inject these dependencies.

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 = metrics.ExportFormat

ExportFormat represents the format for metrics export.

type Exporter

type Exporter = metrics.Exporter

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 = di.Factory

Factory creates a service instance.

type ForgeError

type ForgeError = ferrors.ForgeError

type Gauge

type Gauge = metrics.Gauge

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(cfg *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 = metrics.HealthCallback

HealthCallback is a callback function for health status changes.

type HealthCheck

type HealthCheck = metrics.HealthCheck

HealthCheck defines the interface for health checks.

type HealthCheckFn

type HealthCheckFn = metrics.HealthCheckFn

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 = metrics.HealthCheckerStats

HealthCheckerStats contains statistics about the health checker.

type HealthConfig

type HealthConfig = metrics.HealthConfig

HealthConfig configures health checks.

func DefaultHealthConfig

func DefaultHealthConfig() HealthConfig

DefaultHealthConfig returns default health configuration.

type HealthFeatures added in v0.9.0

type HealthFeatures = metrics.HealthFeatures

HealthFeatures configures health features.

type HealthIntervals added in v0.9.0

type HealthIntervals = metrics.HealthIntervals

HealthIntervals configures health intervals.

type HealthManager

type HealthManager = metrics.HealthManager

HealthManager defines the interface for health checking.

type HealthMetadata added in v0.9.0

type HealthMetadata = metrics.HealthMetadata

HealthMetadata configures health metadata.

type HealthPerformance added in v0.9.0

type HealthPerformance = metrics.HealthPerformance

HealthPerformance configures health performance.

type HealthReport

type HealthReport = metrics.HealthReport

HealthReport represents a comprehensive health report.

func NewHealthReport

func NewHealthReport() *HealthReport

NewHealthReport creates a new health report.

type HealthReportCallback

type HealthReportCallback = metrics.HealthReportCallback

HealthReportCallback is a callback function for health report changes.

type HealthResult

type HealthResult = metrics.HealthResult

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.

type HealthStatus

type HealthStatus = metrics.HealthStatus

HealthStatus represents the health status of a service or component.

const (
	HealthStatusHealthy   HealthStatus = metrics.HealthStatusHealthy
	HealthStatusDegraded  HealthStatus = metrics.HealthStatusDegraded
	HealthStatusUnhealthy HealthStatus = metrics.HealthStatusUnhealthy
	HealthStatusUnknown   HealthStatus = metrics.HealthStatusUnknown
)

type HealthThresholds added in v0.9.0

type HealthThresholds = metrics.HealthThresholds

HealthThresholds configures health thresholds.

type Histogram

type Histogram = metrics.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 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

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

type MetricOption = metrics.MetricOption

MetricOption defines an option for creating a metric.

type MetricType

type MetricType = metrics.MetricType

MetricType represents the type of metric.

const (
	MetricTypeCounter   MetricType = metrics.MetricTypeCounter
	MetricTypeGauge     MetricType = metrics.MetricTypeGauge
	MetricTypeHistogram MetricType = metrics.MetricTypeHistogram
	MetricTypeTimer     MetricType = metrics.MetricTypeTimer
)

type Metrics

type Metrics = metrics.Metrics

Metrics provides telemetry collection.

type MetricsCollection added in v0.9.0

type MetricsCollection = metrics.MetricsCollection

MetricsCollection contains collection configuration.

type MetricsConfig

type MetricsConfig = metrics.MetricsConfig

MetricsConfig configures metrics collection.

type MetricsExporterConfig

type MetricsExporterConfig[T any] = metrics.MetricsExporterConfig[T]

MetricsExporterConfig contains configuration for exporters.

type MetricsFeatures added in v0.9.0

type MetricsFeatures = metrics.MetricsFeatures

MetricsFeatures contains features for metrics collection.

type MetricsLimits added in v0.9.0

type MetricsLimits = metrics.MetricsLimits

MetricsLimits contains limits for metrics collection.

type MetricsStorageConfig

type MetricsStorageConfig[T any] = metrics.MetricsStorageConfig[T]

MetricsStorageConfig 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 = di.RegisterOption

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 (string-based, backward compatible). All dependencies are treated as eager.

func WithDeps added in v0.8.0

func WithDeps(deps ...Dep) RegisterOption

WithDeps declares dependencies with full Dep specs (modes, types). This is the new, more powerful API for declaring 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 = http.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(cfg *RouteConfig)
}

RouteOption configures a single 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(cfg *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 = di.Scope

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 = di.ServiceInfo

ServiceInfo contains diagnostic information.

type Session added in v0.4.0

type Session = http.Session

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

type Timer

type Timer = metrics.Timer

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