di

package
v0.7.3 Latest Latest
Warning

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

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

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GetHealthManager added in v0.5.0

func GetHealthManager(c Container) (shared.HealthManager, error)

GetHealthManager resolves the health manager from the container This is a convenience function for resolving the health manager service The health manager type is defined in the forge package, so this returns the interface.

func GetLogger added in v0.5.0

func GetLogger(c Container) (logger.Logger, error)

GetLogger resolves the logger from the container This is a convenience function for resolving the logger service The logger type is defined in the forge package, so this returns interface{} and should be type-asserted to the appropriate logger interface.

func GetMetrics added in v0.5.0

func GetMetrics(c Container) (metrics.Metrics, error)

GetMetrics resolves the metrics from the container This is a convenience function for resolving the metrics service The metrics type is defined in the forge package, so this returns interface{} and should be type-asserted to the appropriate metrics interface.

func Must

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

Must resolves or panics - use only during startup.

func MustScope

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

MustScope resolves from scope or panics.

func RegisterInterface

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

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

func RegisterScoped

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

RegisterScoped is a convenience wrapper for request-scoped services.

func RegisterScopedInterface

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

RegisterScopedInterface is a convenience wrapper.

func RegisterSingleton

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

RegisterSingleton is a convenience wrapper.

func RegisterSingletonInterface

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

RegisterSingletonInterface is a convenience wrapper.

func RegisterTransient

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

RegisterTransient is a convenience wrapper.

func RegisterTransientInterface

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

RegisterTransientInterface is a convenience wrapper.

func RegisterValue

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

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

func Resolve

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

Resolve with type safety.

func ResolveScope

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

ResolveScope is a helper for resolving from a scope.

Types

type Container

type Container = shared.Container

Container provides dependency injection with lifecycle management.

func NewContainer

func NewContainer() Container

NewContainer creates a new DI container.

type Context

type Context = shared.Context

Context wraps http.Request with convenience methods.

func NewContext

func NewContext(w http.ResponseWriter, r *http.Request, container Container) Context

NewContext creates a new context.

type ContextWithClean

type ContextWithClean interface {
	Cleanup()
}

type Ctx

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

Ctx implements Context interface.

func (*Ctx) Bind

func (c *Ctx) Bind(v any) error

Bind binds request body to a value (auto-detects JSON/XML/multipart).

func (*Ctx) BindJSON

func (c *Ctx) BindJSON(v any) error

BindJSON binds JSON request body.

func (*Ctx) BindRequest added in v0.5.0

func (c *Ctx) BindRequest(v any) error

BindRequest binds and validates request data from all sources (path, query, header, body). This method provides comprehensive request binding that:

  • Binds path parameters from URL path segments (path:"name")
  • Binds query parameters from URL query string (query:"name")
  • Binds headers from HTTP headers (header:"name")
  • Binds body fields from request body (json:"name" or body:"")
  • Validates all fields using validation tags (required, minLength, etc.)

Example:

type CreateUserRequest struct {
    TenantID string `path:"tenantId" description:"Tenant ID"`
    DryRun   bool   `query:"dryRun" default:"false"`
    APIKey   string `header:"X-API-Key" required:"true"`
    Name     string `json:"name" minLength:"1" maxLength:"100"`
}

func handler(ctx forge.Context) error {
    var req CreateUserRequest
    if err := ctx.BindRequest(&req); err != nil {
        return err // Returns ValidationErrors if validation fails
    }
    // All fields are now bound and validated
}

func (*Ctx) BindXML

func (c *Ctx) BindXML(v any) error

BindXML binds XML request body.

func (*Ctx) Bytes

func (c *Ctx) Bytes(code int, data []byte) error

Bytes sends byte response.

func (*Ctx) Cleanup

func (c *Ctx) Cleanup()

Cleanup ends the scope (should be called after request).

func (*Ctx) Container

func (c *Ctx) Container() Container

Container returns the DI container.

func (*Ctx) Context

func (c *Ctx) Context() context.Context

Context returns the request context.

func (*Ctx) Cookie added in v0.4.0

func (c *Ctx) Cookie(name string) (string, error)

Cookie returns a cookie value.

func (*Ctx) DeleteCookie added in v0.4.0

func (c *Ctx) DeleteCookie(name string)

DeleteCookie deletes a cookie by setting MaxAge to -1.

func (*Ctx) DeleteSessionValue added in v0.4.0

func (c *Ctx) DeleteSessionValue(key string)

DeleteSessionValue deletes a value from the current session.

func (*Ctx) DestroySession added in v0.4.0

func (c *Ctx) DestroySession() error

DestroySession removes the current session from the store.

func (*Ctx) Flush added in v0.7.0

func (c *Ctx) Flush() error

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

func (*Ctx) FormFile

func (c *Ctx) FormFile(name string) (multipart.File, *multipart.FileHeader, error)

FormFile retrieves a file from a multipart form.

func (*Ctx) FormFiles

func (c *Ctx) FormFiles(name string) ([]*multipart.FileHeader, error)

FormFiles retrieves multiple files with the same field name from a multipart form.

func (*Ctx) FormValue

func (c *Ctx) FormValue(name string) string

FormValue retrieves a form value from multipart or url-encoded form.

func (*Ctx) FormValues

func (c *Ctx) FormValues(name string) []string

FormValues retrieves all values for a form field.

func (*Ctx) Get

func (c *Ctx) Get(key string) any

Get retrieves a value from the context.

func (*Ctx) GetAllCookies added in v0.4.0

func (c *Ctx) GetAllCookies() map[string]string

GetAllCookies returns all cookies as a map.

func (*Ctx) GetSessionValue added in v0.4.0

func (c *Ctx) GetSessionValue(key string) (any, bool)

GetSessionValue gets a value from the current session.

func (*Ctx) HasCookie added in v0.4.0

func (c *Ctx) HasCookie(name string) bool

HasCookie checks if a cookie exists.

func (*Ctx) Header

func (c *Ctx) Header(key string) string

Header returns a request header.

func (*Ctx) HealthManager

func (c *Ctx) HealthManager() HealthManager

HealthManager returns the health manager.

func (*Ctx) JSON

func (c *Ctx) JSON(code int, v any) error

JSON sends JSON response. If v is a struct with header:"..." tags, those headers are set automatically. If v has a field with body:"" tag, that field's value is serialized instead of the whole struct. If the route has sensitive field cleaning enabled, fields with sensitive:"..." tags are processed.

func (*Ctx) Metrics

func (c *Ctx) Metrics() Metrics

Metrics returns the metrics collector.

func (*Ctx) Must

func (c *Ctx) Must(name string) any

Must resolves a service or panics.

func (*Ctx) MustGet

func (c *Ctx) MustGet(key string) any

MustGet retrieves a value or panics if not found.

func (*Ctx) NoContent

func (c *Ctx) NoContent(code int) error

NoContent sends no content response.

func (*Ctx) Param

func (c *Ctx) Param(name string) string

Param returns a path parameter.

func (*Ctx) ParamBool added in v0.4.0

func (c *Ctx) ParamBool(name string) (bool, error)

ParamBool returns a path parameter as bool.

func (*Ctx) ParamBoolDefault added in v0.4.0

func (c *Ctx) ParamBoolDefault(name string, defaultValue bool) bool

ParamBoolDefault returns a path parameter as bool with default value.

func (*Ctx) ParamFloat64 added in v0.4.0

func (c *Ctx) ParamFloat64(name string) (float64, error)

ParamFloat64 returns a path parameter as float64.

func (*Ctx) ParamFloat64Default added in v0.4.0

func (c *Ctx) ParamFloat64Default(name string, defaultValue float64) float64

ParamFloat64Default returns a path parameter as float64 with default value.

func (*Ctx) ParamInt added in v0.4.0

func (c *Ctx) ParamInt(name string) (int, error)

ParamInt returns a path parameter as int.

func (*Ctx) ParamInt64 added in v0.4.0

func (c *Ctx) ParamInt64(name string) (int64, error)

ParamInt64 returns a path parameter as int64.

func (*Ctx) ParamInt64Default added in v0.4.0

func (c *Ctx) ParamInt64Default(name string, defaultValue int64) int64

ParamInt64Default returns a path parameter as int64 with default value.

func (*Ctx) ParamIntDefault added in v0.4.0

func (c *Ctx) ParamIntDefault(name string, defaultValue int) int

ParamIntDefault returns a path parameter as int with default value.

func (*Ctx) Params

func (c *Ctx) Params() map[string]string

Params returns all path parameters.

func (*Ctx) ParseMultipartForm

func (c *Ctx) ParseMultipartForm(maxMemory int64) error

ParseMultipartForm parses a multipart form with the specified max memory maxMemory: maximum memory in bytes to use for storing files in memory (rest goes to disk) Recommended values: 10MB (10<<20), 32MB (32<<20), 64MB (64<<20).

func (*Ctx) Query

func (c *Ctx) Query(name string) string

Query returns a query parameter.

func (*Ctx) QueryDefault

func (c *Ctx) QueryDefault(name, defaultValue string) string

QueryDefault returns a query parameter with default value.

func (*Ctx) Redirect

func (c *Ctx) Redirect(code int, url string) error

Redirect sends redirect response.

func (*Ctx) Request

func (c *Ctx) Request() *http.Request

Request returns the HTTP request.

func (*Ctx) Resolve

func (c *Ctx) Resolve(name string) (any, error)

Resolve resolves a service from the scope.

func (*Ctx) Response

func (c *Ctx) Response() http.ResponseWriter

Response returns the HTTP response writer.

func (*Ctx) SaveSession added in v0.4.0

func (c *Ctx) SaveSession() error

SaveSession saves the current session to the session store.

func (*Ctx) Scope

func (c *Ctx) Scope() Scope

Scope returns the request scope.

func (*Ctx) Session added in v0.4.0

func (c *Ctx) Session() (shared.Session, error)

Session returns the current session.

func (*Ctx) SessionID added in v0.4.0

func (c *Ctx) SessionID() string

SessionID returns the current session ID.

func (*Ctx) Set

func (c *Ctx) Set(key string, value any)

Set stores a value in the context.

func (*Ctx) SetCookie added in v0.4.0

func (c *Ctx) SetCookie(name, value string, maxAge int)

SetCookie sets a cookie with basic options.

func (*Ctx) SetCookieWithOptions added in v0.4.0

func (c *Ctx) SetCookieWithOptions(name, value string, path, domain string, maxAge int, secure, httpOnly bool)

SetCookieWithOptions sets a cookie with full control over options.

func (*Ctx) SetHeader

func (c *Ctx) SetHeader(key, value string)

SetHeader sets a response header.

func (*Ctx) SetSession added in v0.4.0

func (c *Ctx) SetSession(session shared.Session)

SetSession sets the current session in the context.

func (*Ctx) SetSessionValue added in v0.4.0

func (c *Ctx) SetSessionValue(key string, value any)

SetSessionValue sets a value in the current session.

func (*Ctx) Status

func (c *Ctx) Status(code int) shared.ResponseBuilder

Status sets the HTTP status code and returns a builder for chaining.

func (*Ctx) String

func (c *Ctx) String(code int, s string) error

String sends string response.

func (*Ctx) WithContext

func (c *Ctx) WithContext(ctx context.Context)

WithContext replaces the request context.

func (*Ctx) WriteSSE added in v0.7.0

func (c *Ctx) WriteSSE(event string, data any) error

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.

func (*Ctx) XML

func (c *Ctx) XML(code int, v any) error

XML sends XML response.

type DependencyGraph

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

DependencyGraph manages service dependencies.

func NewDependencyGraph

func NewDependencyGraph() *DependencyGraph

NewDependencyGraph creates a new dependency graph.

func (*DependencyGraph) AddNode

func (g *DependencyGraph) AddNode(name string, dependencies []string)

AddNode adds a node with its dependencies. Nodes are processed in the order they are added (FIFO) when no dependencies exist.

func (*DependencyGraph) TopologicalSort

func (g *DependencyGraph) TopologicalSort() ([]string, error)

TopologicalSort returns nodes in dependency order. Nodes without dependencies maintain their registration order (FIFO). Returns error if circular dependency detected.

type Factory

type Factory = shared.Factory

Factory creates a service instance.

type HealthManager

type HealthManager = shared.HealthManager

type Metrics

type Metrics = shared.Metrics

type RegisterOption

type RegisterOption = shared.RegisterOption

RegisterOption is a configuration option for service registration.

func Scoped

func Scoped() RegisterOption

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

func Singleton

func Singleton() RegisterOption

Singleton makes the service a singleton (default).

func Transient

func Transient() RegisterOption

Transient makes the service created on each resolve.

func WithDIMetadata

func WithDIMetadata(key, value string) RegisterOption

WithDIMetadata adds diagnostic metadata to DI service registration.

func WithDependencies

func WithDependencies(deps ...string) RegisterOption

WithDependencies declares explicit dependencies.

func WithGroup

func WithGroup(group string) RegisterOption

WithGroup adds service to a named group.

type ResponseBuilder

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

ResponseBuilder provides fluent response building.

func (*ResponseBuilder) Bytes

func (rb *ResponseBuilder) Bytes(data []byte) error

Bytes sends a byte response with the configured status.

func (*ResponseBuilder) Header

func (rb *ResponseBuilder) Header(key, value string) shared.ResponseBuilder

Header sets a response header and returns the builder for chaining.

func (*ResponseBuilder) JSON

func (rb *ResponseBuilder) JSON(v any) error

JSON sends a JSON response with the configured status.

func (*ResponseBuilder) NoContent

func (rb *ResponseBuilder) NoContent() error

NoContent sends a no-content response with the configured status.

func (*ResponseBuilder) String

func (rb *ResponseBuilder) String(s string) error

String sends a string response with the configured status.

func (*ResponseBuilder) XML

func (rb *ResponseBuilder) XML(v any) error

XML sends an XML response with the configured status.

type Scope

type Scope = shared.Scope

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

type ServiceInfo

type ServiceInfo = shared.ServiceInfo

ServiceInfo contains diagnostic information.

Jump to

Keyboard shortcuts

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