gocontroller

package
v1.4.0 Latest Latest
Warning

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

Go to latest
Published: May 3, 2026 License: MIT Imports: 32 Imported by: 0

Documentation

Index

Constants

View Source
const DefaultMaxBodyBytes int64 = 1 << 20
View Source
const RequestIDHeader = "X-Request-ID"
View Source
const Version = "v1.4.0"

Version is the current library version.

Variables

View Source
var ErrNotFound = errors.New("route not found")
View Source
var ErrValidation = errors.New("validation failed")

Functions

func ComputeSignature added in v1.4.0

func ComputeSignature(req *http.Request, secret []byte, includeBody, includeMethod, includePath, includeQuery, includeHost bool) []byte

ComputeSignature computes the HMAC-SHA256 signature for a request. Use this in client code to generate signatures.

func ContextValue added in v1.3.0

func ContextValue[T any](ctx *Context, key any) (T, bool)

ContextValue extracts a typed request context value by key.

func DestroySession added in v1.4.0

func DestroySession(ctx *Context, cfg SessionConfig)

DestroySession clears session data and removes the cookie.

func GenerateSignatureHeader added in v1.4.0

func GenerateSignatureHeader(req *http.Request, secret []byte, opts ...func(*SignatureConfig)) string

GenerateSignatureHeader generates a signature header value for a request.

func LifecycleProvider added in v1.4.0

func LifecycleProvider(fn any, name string) any

LifecycleProvider wraps a provider factory to register lifecycle hooks.

func MustContextValue added in v1.3.0

func MustContextValue[T any](ctx *Context, key any, unauthorizedMessage string) (T, error)

MustContextValue extracts a typed request context value by key or returns an unauthorized APIError.

func NewTimerSpan added in v1.4.0

func NewTimerSpan(ctx context.Context, tracer Tracer, name string) func()

NewTimerSpan creates a child span for timing a specific operation.

func NotFoundHTMLOrJSON added in v1.0.1

func NotFoundHTMLOrJSON(notFoundHTMLFile string, jsonMessage string) http.HandlerFunc

NotFoundHTMLOrJSON serves an HTML 404 page for browser requests and JSON for APIs.

func ParseDTO

func ParseDTO[T any](ctx *Context) (T, error)

ParseDTO decodes JSON body into a typed DTO and runs validation.

func RegenerateSession added in v1.4.0

func RegenerateSession(ctx *Context, cfg SessionConfig) error

RegenerateSession creates a new session ID and copies existing data.

func RegisterGeneratedControllerMetadata

func RegisterGeneratedControllerMetadata(controllerPtr any, meta ControllerMetadata)

RegisterGeneratedControllerMetadata is used by generated code.

func ResolveScoped added in v1.4.0

func ResolveScoped[T any](ctx *Context) (T, error)

ResolveScoped resolves a dependency from the request scope.

func SaveFile added in v1.4.0

func SaveFile(destDir string, file *FileHeader) (string, error)

SaveFile saves an uploaded file to the specified directory.

func ServePage added in v1.0.1

func ServePage(publicDir, pageFile string) http.HandlerFunc

ServePage returns a handler that serves a single static page from publicDir.

func SetDefaultValidator

func SetDefaultValidator(v Validator)

SetDefaultValidator sets the process-wide default validator used by Validate and new routers.

func Validate

func Validate(dto any) error

func WebAPIHandler added in v1.0.1

func WebAPIHandler(web http.Handler, api http.Handler, opts HybridOptions) http.Handler

WebAPIHandler composes web and api handlers, reducing manual path-switch boilerplate.

func WithBodySigning added in v1.4.0

func WithBodySigning(cfg *SignatureConfig)

WithBodySigning includes the request body in signature computation.

func WithHostSigning added in v1.4.0

func WithHostSigning(cfg *SignatureConfig)

WithHostSigning includes the host in signature computation.

func WithQuerySigning added in v1.4.0

func WithQuerySigning(cfg *SignatureConfig)

WithQuerySigning includes the query string in signature computation.

func WithTimestampValidation added in v1.4.0

func WithTimestampValidation(maxAge time.Duration) func(*SignatureConfig)

WithTimestampValidation enables timestamp validation with max age.

Types

type APIError added in v1.1.0

type APIError struct {
	StatusCode int
	Code       string
	Message    string
	Details    any
	Cause      error
}

APIError is a standardized error model for HTTP responses.

func BadRequestError added in v1.1.0

func BadRequestError(message string) *APIError

func ConflictError added in v1.1.0

func ConflictError(message string) *APIError

func ForbiddenError added in v1.1.0

func ForbiddenError(message string) *APIError

func InternalError added in v1.1.0

func InternalError(message string) *APIError

func NewAPIError added in v1.1.0

func NewAPIError(status int, code, message string) *APIError

func NotFoundError added in v1.1.0

func NotFoundError(message string) *APIError

func UnauthorizedError added in v1.1.0

func UnauthorizedError(message string) *APIError

func (*APIError) Error added in v1.1.0

func (e *APIError) Error() string

func (*APIError) Unwrap added in v1.1.0

func (e *APIError) Unwrap() error

type App

type App struct {
	Router    *Router
	Container *Container
	Lifecycle *LifecycleManager
	Health    *HealthRegistry
}

func NewApp

func NewApp(root *Module) (*App, error)

func (*App) Handler

func (a *App) Handler() http.Handler

Handler exposes the application router as an http.Handler. This makes it easy to mount in Gin/Echo/Fiber adapter wrappers.

func (*App) Listen

func (a *App) Listen(addr string) error

func (*App) ListenTLS added in v1.4.0

func (a *App) ListenTLS(addr, certFile, keyFile string) error

func (*App) MaxBodyBytes added in v1.4.0

func (a *App) MaxBodyBytes() int64

MaxBodyBytes returns the configured request body limit for JSON binding.

func (*App) NewHTTPServer added in v1.1.0

func (a *App) NewHTTPServer(opts ServerOptions) *http.Server

func (*App) Run added in v1.1.0

func (a *App) Run(ctx context.Context, opts ServerOptions) error

Run starts the HTTP server and gracefully shuts down on context cancellation.

func (*App) SetErrorHandler added in v1.3.0

func (a *App) SetErrorHandler(h ErrorHandlerFunc)

SetErrorHandler overrides router error rendering for this app.

func (*App) SetMaxBodyBytes added in v1.4.0

func (a *App) SetMaxBodyBytes(n int64)

SetMaxBodyBytes sets the maximum request body size used by Context.BindJSON.

func (*App) SetValidator

func (a *App) SetValidator(v Validator)

SetValidator overrides the app/router validator for request DTO validation.

func (*App) Validator

func (a *App) Validator() Validator

Validator returns the validator used by the app/router.

type CORSConfig added in v1.2.0

type CORSConfig struct {
	AllowOrigin      string
	AllowOrigins     []string
	AllowMethods     []string
	AllowHeaders     []string
	AllowCredentials bool
	MaxAge           int
}

type CSRFConfig added in v1.4.0

type CSRFConfig struct {
	Secret        []byte
	CookieName    string
	HeaderName    string
	FormField     string
	Secure        bool
	SameSite      http.SameSite
	Path          string
	Domain        string
	MaxAge        time.Duration
	IgnoreMethods []string
	ErrorHandler  func(*Context) error
}

CSRFConfig configures CSRF protection.

type Container

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

func NewContainer

func NewContainer() *Container

func (*Container) MustResolve

func (c *Container) MustResolve(target any)

func (*Container) Provide

func (c *Container) Provide(value any) error

func (*Container) Resolve

func (c *Container) Resolve(target any) error

func (*Container) WithLifecycle added in v1.4.0

func (c *Container) WithLifecycle(lm *LifecycleManager, modName string)

type Context

type Context struct {
	ResponseWriter http.ResponseWriter
	Request        *http.Request
	Params         map[string]string
	Values         map[string]any
	// contains filtered or unexported fields
}

Context carries request/response helpers for handlers and middleware.

func (*Context) BadRequest added in v1.0.1

func (c *Context) BadRequest(message string) error

func (*Context) BindFile added in v1.4.0

func (c *Context) BindFile(field string) (*FileHeader, error)

BindFile parses a single file upload from a multipart/form-data request.

func (*Context) BindFiles added in v1.4.0

func (c *Context) BindFiles(field string) ([]*FileHeader, error)

BindFiles parses multiple file uploads from a multipart/form-data request.

func (*Context) BindForm added in v1.4.0

func (c *Context) BindForm() (map[string][]string, []*FileHeader, error)

BindForm parses both files and form values from a multipart/form-data request.

func (*Context) BindJSON

func (c *Context) BindJSON(dto any) error

func (*Context) CSRFToken added in v1.4.0

func (c *Context) CSRFToken() string

CSRFToken returns the current request's CSRF token.

func (*Context) Conflict added in v1.0.1

func (c *Context) Conflict(message string) error

func (*Context) Created added in v1.0.1

func (c *Context) Created(data any) error

func (*Context) Error added in v1.0.1

func (c *Context) Error(status int, message string) error

Error returns a standard error envelope: {"success": false, "error": ...}.

func (*Context) Forbidden added in v1.0.1

func (c *Context) Forbidden(message string) error

func (*Context) Get

func (c *Context) Get(key string) (any, bool)

func (*Context) InternalError added in v1.0.1

func (c *Context) InternalError(message string) error

func (*Context) JSON

func (c *Context) JSON(status int, body any) error

func (*Context) NoContent added in v1.0.1

func (c *Context) NoContent() error

func (*Context) NotFound added in v1.0.1

func (c *Context) NotFound(message string) error

func (*Context) OK added in v1.0.1

func (c *Context) OK(data any) error

func (*Context) Param

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

func (*Context) RecordMetric added in v1.4.0

func (c *Context) RecordMetric(key string, value any)

RecordMetric records a custom metric attribute on the current span.

func (*Context) RequestID added in v1.1.0

func (c *Context) RequestID() string

func (*Context) Set

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

func (*Context) Success added in v1.0.1

func (c *Context) Success(status int, data any) error

Success returns a standard success envelope: {"success": true, "data": ...}.

func (*Context) Text

func (c *Context) Text(status int, value string) error

func (*Context) TraceID added in v1.4.0

func (c *Context) TraceID() string

TraceID returns the current trace ID if available.

func (*Context) Unauthorized added in v1.0.1

func (c *Context) Unauthorized(message string) error

type Controller

type Controller interface {
	RegisterRoutes(*RouteGroup)
}

type ControllerMetadata

type ControllerMetadata struct {
	Prefix     string
	Middleware []Middleware
	Routes     []RouteMetadata
}

ControllerMetadata is decorator-like route metadata for a controller.

type DecoratedController

type DecoratedController interface {
	ControllerMetadata() ControllerMetadata
}

DecoratedController declares controller metadata for auto route binding.

type ErrorHandlerFunc added in v1.3.0

type ErrorHandlerFunc func(*Context, error)

type Event added in v1.4.0

type Event struct {
	Name     string
	Payload  any
	Metadata map[string]string
}

Event represents a domain event.

type EventBus added in v1.4.0

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

EventBus provides pub/sub event dispatching.

func EventBusFromContext added in v1.4.0

func EventBusFromContext(ctx *Context) *EventBus

EventBusFromContext retrieves the event bus from context.

func NewEventBus added in v1.4.0

func NewEventBus() *EventBus

NewEventBus creates a new event bus.

func (*EventBus) Emit added in v1.4.0

func (b *EventBus) Emit(ctx context.Context, event Event) error

Emit fires an event to all registered handlers.

func (*EventBus) EmitAsync added in v1.4.0

func (b *EventBus) EmitAsync(ctx context.Context, event Event)

EmitAsync fires an event asynchronously in a goroutine.

func (*EventBus) EmitSync added in v1.4.0

func (b *EventBus) EmitSync(ctx context.Context, event Event) error

EmitSync fires an event synchronously, blocking until all handlers complete.

func (*EventBus) Off added in v1.4.0

func (b *EventBus) Off(name string)

Off removes all handlers for an event name.

func (*EventBus) On added in v1.4.0

func (b *EventBus) On(name string, handler EventHandler)

On registers a handler for an event name.

func (*EventBus) Once added in v1.4.0

func (b *EventBus) Once(name string, handler EventHandler)

Once registers a handler that fires only once.

type EventHandler added in v1.4.0

type EventHandler func(ctx context.Context, event Event) error

EventHandler processes an event.

type FileHeader added in v1.4.0

type FileHeader struct {
	Name     string
	Header   *multipart.FileHeader
	OpenFunc func() (multipart.File, error)
}

FileHeader represents an uploaded file.

func (*FileHeader) Open added in v1.4.0

func (f *FileHeader) Open() (multipart.File, error)

Open opens the uploaded file.

type GoPlaygroundValidator

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

GoPlaygroundValidator uses github.com/go-playground/validator/v10.

func NewGoPlaygroundValidator

func NewGoPlaygroundValidator() *GoPlaygroundValidator

func (*GoPlaygroundValidator) Validate

func (g *GoPlaygroundValidator) Validate(dto any) error

type HTTPError

type HTTPError struct {
	StatusCode int
	Message    string
}

func NewHTTPError

func NewHTTPError(statusCode int, message string) *HTTPError

func (*HTTPError) Error

func (e *HTTPError) Error() string

type HandlerFunc

type HandlerFunc func(*Context) error

type HealthCheckerFunc added in v1.4.0

type HealthCheckerFunc func() HealthStatus

HealthCheckerFunc returns the health status of a component.

type HealthRegistry added in v1.4.0

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

HealthRegistry manages multiple health checkers.

func NewHealthRegistry added in v1.4.0

func NewHealthRegistry() *HealthRegistry

NewHealthRegistry creates a new health check registry.

func (*HealthRegistry) HealthMiddleware added in v1.4.0

func (hr *HealthRegistry) HealthMiddleware(livenessPath, readinessPath string) Middleware

HealthMiddleware returns a middleware that serves health endpoints.

func (*HealthRegistry) IsReady added in v1.4.0

func (r *HealthRegistry) IsReady() bool

IsReady returns whether the application is ready.

func (*HealthRegistry) LivenessHandler added in v1.4.0

func (hr *HealthRegistry) LivenessHandler() http.HandlerFunc

LivenessHandler returns a standalone http.HandlerFunc for liveness.

func (*HealthRegistry) MarkReady added in v1.4.0

func (r *HealthRegistry) MarkReady()

MarkReady signals the application is ready to serve traffic.

func (*HealthRegistry) ReadinessHandler added in v1.4.0

func (hr *HealthRegistry) ReadinessHandler() http.HandlerFunc

ReadinessHandler returns a standalone http.HandlerFunc for readiness.

func (*HealthRegistry) RegisterLiveness added in v1.4.0

func (r *HealthRegistry) RegisterLiveness(name string, fn HealthCheckerFunc)

RegisterLiveness adds a liveness probe check.

func (*HealthRegistry) RegisterReadiness added in v1.4.0

func (r *HealthRegistry) RegisterReadiness(name string, fn HealthCheckerFunc)

RegisterReadiness adds a readiness probe check.

func (*HealthRegistry) Uptime added in v1.4.0

func (r *HealthRegistry) Uptime() time.Duration

Uptime returns the time since the registry was created.

type HealthStatus added in v1.4.0

type HealthStatus struct {
	Status  string    `json:"status"`
	Checked time.Time `json:"checked_at"`
	Details any       `json:"details,omitempty"`
}

HealthStatus represents the result of a health check.

type HybridOptions added in v1.0.1

type HybridOptions struct {
	WebExactPaths              []string
	WebPathPrefixes            []string
	TreatSingleSegmentGETAsWeb bool
}

HybridOptions controls how WebAPIHandler routes traffic to web or api handlers.

type IdempotencyConfig added in v1.4.0

type IdempotencyConfig struct {
	Store        *IdempotencyStore
	HeaderName   string
	Methods      []string
	SkipOnHeader func(*Context) bool
}

IdempotencyConfig configures the idempotency middleware.

type IdempotencyStore added in v1.4.0

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

IdempotencyStore stores idempotent request responses.

func NewIdempotencyStore added in v1.4.0

func NewIdempotencyStore(ttl time.Duration, maxSize int) *IdempotencyStore

NewIdempotencyStore creates a new in-memory idempotency store.

type JWTClaims added in v1.4.0

type JWTClaims map[string]any

JWTClaims represents decoded JWT payload.

func JWTClaimsFromContext added in v1.4.0

func JWTClaimsFromContext(ctx *Context) (JWTClaims, bool)

JWTClaimsFromContext extracts JWT claims from request context.

func (JWTClaims) Audience added in v1.4.0

func (c JWTClaims) Audience() []string

Audience returns the "aud" claim.

func (JWTClaims) ExpiresAt added in v1.4.0

func (c JWTClaims) ExpiresAt() (time.Time, bool)

ExpiresAt returns the "exp" claim as time.Time.

func (JWTClaims) IssuedAt added in v1.4.0

func (c JWTClaims) IssuedAt() (time.Time, bool)

IssuedAt returns the "iat" claim as time.Time.

func (JWTClaims) Issuer added in v1.4.0

func (c JWTClaims) Issuer() string

Issuer returns the "iss" claim.

func (JWTClaims) Subject added in v1.4.0

func (c JWTClaims) Subject() string

Subject returns the "sub" claim.

type JWTConfig added in v1.4.0

type JWTConfig struct {
	SecretKey       []byte
	PublicKey       *rsa.PublicKey
	Algorithm       string
	ClaimsValidator func(JWTClaims) error
	HeaderName      string
	SchemePrefix    string
}

JWTConfig configures JWT verification.

type Lifecycle added in v1.4.0

type Lifecycle interface {
	OnModuleInit(ctx context.Context) error
	OnModuleDestroy(ctx context.Context) error
}

Lifecycle defines hooks for module initialization and cleanup.

type LifecycleDestroyOnly added in v1.4.0

type LifecycleDestroyOnly interface {
	OnModuleDestroy(ctx context.Context) error
}

LifecycleDestroyOnly implements only OnModuleDestroy.

type LifecycleInitOnly added in v1.4.0

type LifecycleInitOnly interface {
	OnModuleInit(ctx context.Context) error
}

LifecycleInitOnly implements only OnModuleInit.

type LifecycleManager added in v1.4.0

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

LifecycleManager tracks and executes lifecycle hooks.

func NewLifecycleManager added in v1.4.0

func NewLifecycleManager() *LifecycleManager

NewLifecycleManager creates a new lifecycle manager.

func (*LifecycleManager) Destroy added in v1.4.0

func (m *LifecycleManager) Destroy(ctx context.Context) error

Destroy executes OnModuleDestroy hooks in reverse order.

func (*LifecycleManager) Init added in v1.4.0

func (m *LifecycleManager) Init(ctx context.Context) error

Init executes OnModuleInit hooks for all registered instances.

func (*LifecycleManager) Register added in v1.4.0

func (m *LifecycleManager) Register(instance any, name string)

Register adds an instance to the lifecycle manager.

type Middleware

type Middleware func(HandlerFunc) HandlerFunc

func AdaptHTTPMiddleware added in v1.0.1

func AdaptHTTPMiddleware(httpMW func(http.Handler) http.Handler) Middleware

AdaptHTTPMiddleware adapts a standard net/http middleware into gocontroller middleware.

func CORS added in v1.2.0

func CORS(config CORSConfig) Middleware

CORS applies a basic CORS policy and handles OPTIONS preflight.

func CSRF added in v1.4.0

func CSRF(cfg CSRFConfig) Middleware

CSRF returns a middleware that protects against cross-site request forgery.

func CSRFTokenHeader added in v1.4.0

func CSRFTokenHeader() Middleware

CSRFTokenMiddleware adds CSRF token to response header for SPAs.

func EventMiddleware added in v1.4.0

func EventMiddleware(bus *EventBus) Middleware

EventMiddleware returns a middleware that emits events on request lifecycle.

func Idempotency added in v1.4.0

func Idempotency(cfg IdempotencyConfig) Middleware

Idempotency returns a middleware that caches responses for duplicate requests.

func JWT added in v1.4.0

func JWT(cfg JWTConfig) Middleware

JWT returns a middleware that validates JWT tokens from the Authorization header.

func ModuleName added in v1.3.1

func ModuleName(name string) Middleware

ModuleName annotates request context with a module name for logging/metrics.

func Recovery added in v1.1.0

func Recovery(config RecoveryConfig) Middleware

Recovery catches panics and returns a standardized 500 error response.

func RequestID added in v1.1.0

func RequestID() Middleware

RequestID injects a request id into Context and response header.

func RequestLogger added in v1.0.1

func RequestLogger() Middleware

RequestLogger logs method, path, status time around each request.

func RequestSignature added in v1.4.0

func RequestSignature(cfg SignatureConfig) Middleware

RequestSignature returns a middleware that verifies HMAC-SHA256 request signatures.

func RequireContextValue added in v1.3.0

func RequireContextValue(key any, unauthorizedMessage string) Middleware

RequireContextValue ensures a request context value exists before handler execution. Useful for auth checks after upstream middleware populates request context.

func RequireJWT added in v1.4.0

func RequireJWT(cfg JWTConfig) Middleware

RequireJWT ensures a valid JWT is present before proceeding.

func SchedulerMiddleware added in v1.4.0

func SchedulerMiddleware(scheduler *Scheduler) Middleware

SchedulerMiddleware adds the scheduler to app context and manages lifecycle.

func ScopedDI added in v1.4.0

func ScopedDI(cfg ScopeConfig) Middleware

ScopedDI returns a middleware that creates a request-scoped DI container.

func SecurityHeaders added in v1.2.0

func SecurityHeaders() Middleware

SecurityHeaders adds common hardening headers to responses.

func SessionMiddleware added in v1.4.0

func SessionMiddleware(cfg SessionConfig) Middleware

SessionMiddleware returns a middleware that manages encrypted cookie sessions.

func Tracing added in v1.4.0

func Tracing(cfg TelemetryConfig) Middleware

Tracing returns a middleware that creates a span for each request.

type Module

type Module struct {
	Name        string
	Prefix      string
	Providers   []any
	Controllers []any
	Imports     []*Module
	Middleware  []Middleware
}

Module models a NestJS-like module graph.

type NoOpSpan added in v1.4.0

type NoOpSpan struct{}

NoOpSpan is a span that does nothing.

func (NoOpSpan) End added in v1.4.0

func (s NoOpSpan) End()

func (NoOpSpan) SetAttribute added in v1.4.0

func (s NoOpSpan) SetAttribute(key string, value any)

func (NoOpSpan) SetStatus added in v1.4.0

func (s NoOpSpan) SetStatus(code StatusCode, description string)

type NoOpTracer added in v1.4.0

type NoOpTracer struct{}

NoOpTracer is a tracer that does nothing.

func (NoOpTracer) Start added in v1.4.0

func (t NoOpTracer) Start(ctx context.Context, name string, opts ...SpanOption) (context.Context, Span)

type PaginationConfig added in v1.4.0

type PaginationConfig struct {
	DefaultPage  int
	DefaultLimit int
	MaxLimit     int
}

PaginationConfig configures default pagination behavior.

type PaginationOptions added in v1.4.0

type PaginationOptions struct {
	Page     int
	Limit    int
	Offset   int
	Sort     string
	Order    string
	Total    int64
	Cursor   string
	HasMore  bool
	NextPage int
}

PaginationOptions holds parsed pagination parameters.

func ParsePagination added in v1.4.0

func ParsePagination(u *url.URL, cfg ...PaginationConfig) PaginationOptions

ParsePagination extracts pagination parameters from the request query string.

func ParsePaginationFromContext added in v1.4.0

func ParsePaginationFromContext(ctx *Context, cfg ...PaginationConfig) PaginationOptions

ParsePaginationFromContext extracts pagination from the request context URL.

func (*PaginationOptions) JSONResponse added in v1.4.0

func (p *PaginationOptions) JSONResponse(data any) map[string]any

JSONResponse returns a standardized pagination JSON response body.

func (*PaginationOptions) LinkHeader added in v1.4.0

func (p *PaginationOptions) LinkHeader(baseURL string) string

LinkHeader generates a RFC 5988 Link header for pagination.

func (*PaginationOptions) SetTotal added in v1.4.0

func (p *PaginationOptions) SetTotal(total int64)

SetTotal calculates pagination metadata from total item count.

type RateLimitConfig added in v1.4.0

type RateLimitConfig struct {
	Rate    float64
	Burst   int
	Cleanup time.Duration
	MaxKeys int
	KeyFunc func(*Context) string
	Handler func(*Context)
}

RateLimitConfig configures a rate limiter middleware.

type RateLimiter added in v1.4.0

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

RateLimiter implements a token bucket rate limiter.

func NewRateLimiter added in v1.4.0

func NewRateLimiter(cfg RateLimitConfig) *RateLimiter

NewRateLimiter creates a new token bucket rate limiter.

func (*RateLimiter) Allow added in v1.4.0

func (rl *RateLimiter) Allow(key string) bool

Allow checks if a key is allowed to proceed.

func (*RateLimiter) RateLimit added in v1.4.0

func (rl *RateLimiter) RateLimit() Middleware

RateLimit returns a middleware that applies the rate limiter.

type RecoveryConfig added in v1.1.0

type RecoveryConfig struct {
	IncludeStack bool
	Logf         func(format string, args ...any)
}

type RouteGroup

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

func (*RouteGroup) DELETE

func (g *RouteGroup) DELETE(path string, handler HandlerFunc, middleware ...Middleware)

func (*RouteGroup) GET

func (g *RouteGroup) GET(path string, handler HandlerFunc, middleware ...Middleware)

func (*RouteGroup) Group

func (g *RouteGroup) Group(prefix string, middleware ...Middleware) *RouteGroup

func (*RouteGroup) OPTIONS

func (g *RouteGroup) OPTIONS(path string, handler HandlerFunc, middleware ...Middleware)

func (*RouteGroup) PATCH

func (g *RouteGroup) PATCH(path string, handler HandlerFunc, middleware ...Middleware)

func (*RouteGroup) POST

func (g *RouteGroup) POST(path string, handler HandlerFunc, middleware ...Middleware)

func (*RouteGroup) PUT

func (g *RouteGroup) PUT(path string, handler HandlerFunc, middleware ...Middleware)

type RouteMetadata

type RouteMetadata struct {
	Method     string
	Path       string
	Handler    string
	Middleware []Middleware
}

RouteMetadata describes a single route in a controller.

func DELETE

func DELETE(path, handler string, middleware ...Middleware) RouteMetadata

func GET

func GET(path, handler string, middleware ...Middleware) RouteMetadata

func OPTIONS

func OPTIONS(path, handler string, middleware ...Middleware) RouteMetadata

func PATCH

func PATCH(path, handler string, middleware ...Middleware) RouteMetadata

func POST

func POST(path, handler string, middleware ...Middleware) RouteMetadata

func PUT

func PUT(path, handler string, middleware ...Middleware) RouteMetadata

type Router

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

Router provides method-based routing and middleware composition.

func NewRouter

func NewRouter() *Router

func (*Router) DELETE

func (r *Router) DELETE(path string, handler HandlerFunc, middleware ...Middleware)

func (*Router) GET

func (r *Router) GET(path string, handler HandlerFunc, middleware ...Middleware)

func (*Router) Group

func (r *Router) Group(prefix string, middleware ...Middleware) *RouteGroup

func (*Router) MaxBodyBytes added in v1.4.0

func (r *Router) MaxBodyBytes() int64

MaxBodyBytes returns the configured request body limit for JSON binding.

func (*Router) OPTIONS

func (r *Router) OPTIONS(path string, handler HandlerFunc, middleware ...Middleware)

func (*Router) PATCH

func (r *Router) PATCH(path string, handler HandlerFunc, middleware ...Middleware)

func (*Router) POST

func (r *Router) POST(path string, handler HandlerFunc, middleware ...Middleware)

func (*Router) PUT

func (r *Router) PUT(path string, handler HandlerFunc, middleware ...Middleware)

func (*Router) ServeHTTP

func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request)

func (*Router) SetErrorHandler added in v1.3.0

func (r *Router) SetErrorHandler(h ErrorHandlerFunc)

SetErrorHandler overrides route-handler error rendering.

func (*Router) SetMaxBodyBytes added in v1.4.0

func (r *Router) SetMaxBodyBytes(n int64)

SetMaxBodyBytes sets the maximum request body size used by Context.BindJSON. Values <= 0 disable the framework-level body limit.

func (*Router) SetValidator

func (r *Router) SetValidator(v Validator)

SetValidator overrides validation engine used by Context.BindJSON for this router.

func (*Router) Use

func (r *Router) Use(middleware ...Middleware)

func (*Router) Validator

func (r *Router) Validator() Validator

Validator returns the validation engine currently attached to this router.

type Scheduler added in v1.4.0

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

Scheduler manages scheduled tasks.

func GetScheduler added in v1.4.0

func GetScheduler(ctx *Context) *Scheduler

GetScheduler retrieves the scheduler from context.

func NewScheduler added in v1.4.0

func NewScheduler() *Scheduler

NewScheduler creates a new task scheduler.

func (*Scheduler) AddTask added in v1.4.0

func (s *Scheduler) AddTask(name, schedule string, fn TaskFunc) error

AddTask registers a task with a cron-like schedule.

func (*Scheduler) RemoveTask added in v1.4.0

func (s *Scheduler) RemoveTask(name string) bool

RemoveTask removes a task by name.

func (*Scheduler) Start added in v1.4.0

func (s *Scheduler) Start(ctx context.Context)

Start begins executing scheduled tasks.

func (*Scheduler) Stop added in v1.4.0

func (s *Scheduler) Stop()

Stop stops the scheduler.

func (*Scheduler) TaskList added in v1.4.0

func (s *Scheduler) TaskList() string

TaskList returns a formatted string of all tasks.

func (*Scheduler) Tasks added in v1.4.0

func (s *Scheduler) Tasks() []*Task

Tasks returns all registered tasks.

type ScopeConfig added in v1.4.0

type ScopeConfig struct {
	ScopedProviders []any
	OnCreate        func(*ScopedContainer) error
	OnDispose       func(*ScopedContainer) error
}

ScopeConfig configures scoped DI middleware.

type ScopedContainer added in v1.4.0

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

ScopedContainer provides request-level dependency injection.

func GetScope added in v1.4.0

func GetScope(ctx *Context) *ScopedContainer

GetScope retrieves the scoped container from context.

func NewScopedContainer added in v1.4.0

func NewScopedContainer(parent *Container) *ScopedContainer

NewScopedContainer creates a new scoped container with a parent.

func (*ScopedContainer) Provide added in v1.4.0

func (s *ScopedContainer) Provide(value any) error

Provide registers a value in the current scope.

func (*ScopedContainer) Resolve added in v1.4.0

func (s *ScopedContainer) Resolve(target any) error

Resolve resolves a dependency from the scope or parent container.

type ServerOptions added in v1.1.0

type ServerOptions struct {
	Addr              string
	ReadTimeout       time.Duration
	ReadHeaderTimeout time.Duration
	WriteTimeout      time.Duration
	IdleTimeout       time.Duration
	ShutdownTimeout   time.Duration
	MaxHeaderBytes    int
}

type Session added in v1.4.0

type Session struct {
	ID    string
	Data  map[string]any
	IsNew bool
	// contains filtered or unexported fields
}

Session stores key-value pairs for a user session.

func GetSession added in v1.4.0

func GetSession(ctx *Context) *Session

GetSession retrieves the current session from context.

func (*Session) Delete added in v1.4.0

func (s *Session) Delete(key string)

func (*Session) GenerateID added in v1.4.0

func (s *Session) GenerateID() error

func (*Session) Get added in v1.4.0

func (s *Session) Get(key string) (any, bool)

func (*Session) GetString added in v1.4.0

func (s *Session) GetString(key string) (string, bool)

func (*Session) IsExpired added in v1.4.0

func (s *Session) IsExpired() bool

func (*Session) Set added in v1.4.0

func (s *Session) Set(key string, value any)

type SessionConfig added in v1.4.0

type SessionConfig struct {
	Secret     []byte
	CookieName string
	MaxAge     time.Duration
	Secure     bool
	HttpOnly   bool
	SameSite   http.SameSite
	Path       string
	Domain     string
}

SessionConfig configures session management.

type SignatureConfig added in v1.4.0

type SignatureConfig struct {
	Secret           []byte
	HeaderName       string
	TimestampHeader  string
	MaxAge           time.Duration
	IncludeBody      bool
	IncludeMethod    bool
	IncludePath      bool
	IncludeQuery     bool
	IncludeHost      bool
	IncludeTimestamp bool
	SkipPaths        []string
	ErrorHandler     func(*Context) error
}

SignatureConfig configures request signature verification.

type Span added in v1.4.0

type Span interface {
	SetAttribute(key string, value any)
	SetStatus(code StatusCode, description string)
	End()
}

Span represents a single operation trace span.

func SpanFromContext added in v1.4.0

func SpanFromContext(ctx *Context) Span

SpanFromContext retrieves the current trace span from context.

type SpanConfig added in v1.4.0

type SpanConfig struct {
	Attributes map[string]any
	Kind       SpanKind
}

SpanConfig holds span creation options.

type SpanKind added in v1.4.0

type SpanKind int

SpanKind represents the type of span.

const (
	SpanKindInternal SpanKind = iota
	SpanKindServer
	SpanKindClient
)

type SpanOption added in v1.4.0

type SpanOption func(*SpanConfig)

SpanOption configures span creation.

func WithAttributes added in v1.4.0

func WithAttributes(attrs map[string]any) SpanOption

WithAttributes adds attributes to a span.

func WithSpanKind added in v1.4.0

func WithSpanKind(kind SpanKind) SpanOption

WithSpanKind sets the span kind.

type StatusCode added in v1.4.0

type StatusCode int

StatusCode represents span status.

const (
	StatusUnset StatusCode = iota
	StatusOk
	StatusError
)

type Task added in v1.4.0

type Task struct {
	Name     string
	Schedule string
	Func     TaskFunc
	LastRun  time.Time
	NextRun  time.Time
	Enabled  bool
}

Task represents a scheduled task.

func (*Task) String added in v1.4.0

func (t *Task) String() string

type TaskFunc added in v1.4.0

type TaskFunc func(ctx context.Context) error

TaskFunc is a function executed by the scheduler.

type TelemetryConfig added in v1.4.0

type TelemetryConfig struct {
	Tracer         Tracer
	ServiceName    string
	ServiceVersion string
	IncludeHeaders []string
	IncludeQuery   bool
	SkipPaths      []string
}

TelemetryConfig configures the tracing middleware.

type Tracer added in v1.4.0

type Tracer interface {
	Start(ctx context.Context, name string, opts ...SpanOption) (context.Context, Span)
}

Tracer creates spans for distributed tracing.

type ValidationError

type ValidationError struct {
	Field   string
	Rule    string
	Message string
}

type ValidationErrors

type ValidationErrors []ValidationError

func (ValidationErrors) Error

func (ve ValidationErrors) Error() string

func (ValidationErrors) Unwrap

func (ve ValidationErrors) Unwrap() error

type Validator

type Validator interface {
	Validate(any) error
}

Validator is a pluggable validation engine.

func DefaultValidator

func DefaultValidator() Validator

DefaultValidator returns the process-wide default validator.

type ValidatorFunc

type ValidatorFunc func(any) error

ValidatorFunc adapts a function into a Validator.

func (ValidatorFunc) Validate

func (f ValidatorFunc) Validate(v any) error

Jump to

Keyboard shortcuts

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