Documentation
¶
Index ¶
- Constants
- Variables
- func ComputeSignature(req *http.Request, secret []byte, ...) []byte
- func ContextValue[T any](ctx *Context, key any) (T, bool)
- func DestroySession(ctx *Context, cfg SessionConfig)
- func GenerateSignatureHeader(req *http.Request, secret []byte, opts ...func(*SignatureConfig)) string
- func LifecycleProvider(fn any, name string) any
- func MustContextValue[T any](ctx *Context, key any, unauthorizedMessage string) (T, error)
- func NewTimerSpan(ctx context.Context, tracer Tracer, name string) func()
- func NotFoundHTMLOrJSON(notFoundHTMLFile string, jsonMessage string) http.HandlerFunc
- func ParseDTO[T any](ctx *Context) (T, error)
- func RegenerateSession(ctx *Context, cfg SessionConfig) error
- func RegisterGeneratedControllerMetadata(controllerPtr any, meta ControllerMetadata)
- func ResolveScoped[T any](ctx *Context) (T, error)
- func SaveFile(destDir string, file *FileHeader) (string, error)
- func ServePage(publicDir, pageFile string) http.HandlerFunc
- func SetDefaultValidator(v Validator)
- func Validate(dto any) error
- func WebAPIHandler(web http.Handler, api http.Handler, opts HybridOptions) http.Handler
- func WithBodySigning(cfg *SignatureConfig)
- func WithHostSigning(cfg *SignatureConfig)
- func WithQuerySigning(cfg *SignatureConfig)
- func WithTimestampValidation(maxAge time.Duration) func(*SignatureConfig)
- type APIError
- func BadRequestError(message string) *APIError
- func ConflictError(message string) *APIError
- func ForbiddenError(message string) *APIError
- func InternalError(message string) *APIError
- func NewAPIError(status int, code, message string) *APIError
- func NotFoundError(message string) *APIError
- func UnauthorizedError(message string) *APIError
- type App
- func (a *App) Handler() http.Handler
- func (a *App) Listen(addr string) error
- func (a *App) ListenTLS(addr, certFile, keyFile string) error
- func (a *App) MaxBodyBytes() int64
- func (a *App) NewHTTPServer(opts ServerOptions) *http.Server
- func (a *App) Run(ctx context.Context, opts ServerOptions) error
- func (a *App) SetErrorHandler(h ErrorHandlerFunc)
- func (a *App) SetMaxBodyBytes(n int64)
- func (a *App) SetValidator(v Validator)
- func (a *App) Validator() Validator
- type CORSConfig
- type CSRFConfig
- type Container
- type Context
- func (c *Context) BadRequest(message string) error
- func (c *Context) BindFile(field string) (*FileHeader, error)
- func (c *Context) BindFiles(field string) ([]*FileHeader, error)
- func (c *Context) BindForm() (map[string][]string, []*FileHeader, error)
- func (c *Context) BindJSON(dto any) error
- func (c *Context) CSRFToken() string
- func (c *Context) Conflict(message string) error
- func (c *Context) Created(data any) error
- func (c *Context) Error(status int, message string) error
- func (c *Context) Forbidden(message string) error
- func (c *Context) Get(key string) (any, bool)
- func (c *Context) InternalError(message string) error
- func (c *Context) JSON(status int, body any) error
- func (c *Context) NoContent() error
- func (c *Context) NotFound(message string) error
- func (c *Context) OK(data any) error
- func (c *Context) Param(name string) string
- func (c *Context) RecordMetric(key string, value any)
- func (c *Context) RequestID() string
- func (c *Context) Set(key string, value any)
- func (c *Context) Success(status int, data any) error
- func (c *Context) Text(status int, value string) error
- func (c *Context) TraceID() string
- func (c *Context) Unauthorized(message string) error
- type Controller
- type ControllerMetadata
- type DecoratedController
- type ErrorHandlerFunc
- type Event
- type EventBus
- func (b *EventBus) Emit(ctx context.Context, event Event) error
- func (b *EventBus) EmitAsync(ctx context.Context, event Event)
- func (b *EventBus) EmitSync(ctx context.Context, event Event) error
- func (b *EventBus) Off(name string)
- func (b *EventBus) On(name string, handler EventHandler)
- func (b *EventBus) Once(name string, handler EventHandler)
- type EventHandler
- type FileHeader
- type GoPlaygroundValidator
- type HTTPError
- type HandlerFunc
- type HealthCheckerFunc
- type HealthRegistry
- func (hr *HealthRegistry) HealthMiddleware(livenessPath, readinessPath string) Middleware
- func (r *HealthRegistry) IsReady() bool
- func (hr *HealthRegistry) LivenessHandler() http.HandlerFunc
- func (r *HealthRegistry) MarkReady()
- func (hr *HealthRegistry) ReadinessHandler() http.HandlerFunc
- func (r *HealthRegistry) RegisterLiveness(name string, fn HealthCheckerFunc)
- func (r *HealthRegistry) RegisterReadiness(name string, fn HealthCheckerFunc)
- func (r *HealthRegistry) Uptime() time.Duration
- type HealthStatus
- type HybridOptions
- type IdempotencyConfig
- type IdempotencyStore
- type JWTClaims
- type JWTConfig
- type Lifecycle
- type LifecycleDestroyOnly
- type LifecycleInitOnly
- type LifecycleManager
- type Middleware
- func AdaptHTTPMiddleware(httpMW func(http.Handler) http.Handler) Middleware
- func CORS(config CORSConfig) Middleware
- func CSRF(cfg CSRFConfig) Middleware
- func CSRFTokenHeader() Middleware
- func EventMiddleware(bus *EventBus) Middleware
- func Idempotency(cfg IdempotencyConfig) Middleware
- func JWT(cfg JWTConfig) Middleware
- func ModuleName(name string) Middleware
- func Recovery(config RecoveryConfig) Middleware
- func RequestID() Middleware
- func RequestLogger() Middleware
- func RequestSignature(cfg SignatureConfig) Middleware
- func RequireContextValue(key any, unauthorizedMessage string) Middleware
- func RequireJWT(cfg JWTConfig) Middleware
- func SchedulerMiddleware(scheduler *Scheduler) Middleware
- func ScopedDI(cfg ScopeConfig) Middleware
- func SecurityHeaders() Middleware
- func SessionMiddleware(cfg SessionConfig) Middleware
- func Tracing(cfg TelemetryConfig) Middleware
- type Module
- type NoOpSpan
- type NoOpTracer
- type PaginationConfig
- type PaginationOptions
- type RateLimitConfig
- type RateLimiter
- type RecoveryConfig
- type RouteGroup
- func (g *RouteGroup) DELETE(path string, handler HandlerFunc, middleware ...Middleware)
- func (g *RouteGroup) GET(path string, handler HandlerFunc, middleware ...Middleware)
- func (g *RouteGroup) Group(prefix string, middleware ...Middleware) *RouteGroup
- func (g *RouteGroup) OPTIONS(path string, handler HandlerFunc, middleware ...Middleware)
- func (g *RouteGroup) PATCH(path string, handler HandlerFunc, middleware ...Middleware)
- func (g *RouteGroup) POST(path string, handler HandlerFunc, middleware ...Middleware)
- func (g *RouteGroup) PUT(path string, handler HandlerFunc, middleware ...Middleware)
- type RouteMetadata
- func DELETE(path, handler string, middleware ...Middleware) RouteMetadata
- func GET(path, handler string, middleware ...Middleware) RouteMetadata
- func OPTIONS(path, handler string, middleware ...Middleware) RouteMetadata
- func PATCH(path, handler string, middleware ...Middleware) RouteMetadata
- func POST(path, handler string, middleware ...Middleware) RouteMetadata
- func PUT(path, handler string, middleware ...Middleware) RouteMetadata
- type Router
- func (r *Router) DELETE(path string, handler HandlerFunc, middleware ...Middleware)
- func (r *Router) GET(path string, handler HandlerFunc, middleware ...Middleware)
- func (r *Router) Group(prefix string, middleware ...Middleware) *RouteGroup
- func (r *Router) MaxBodyBytes() int64
- func (r *Router) OPTIONS(path string, handler HandlerFunc, middleware ...Middleware)
- func (r *Router) PATCH(path string, handler HandlerFunc, middleware ...Middleware)
- func (r *Router) POST(path string, handler HandlerFunc, middleware ...Middleware)
- func (r *Router) PUT(path string, handler HandlerFunc, middleware ...Middleware)
- func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request)
- func (r *Router) SetErrorHandler(h ErrorHandlerFunc)
- func (r *Router) SetMaxBodyBytes(n int64)
- func (r *Router) SetValidator(v Validator)
- func (r *Router) Use(middleware ...Middleware)
- func (r *Router) Validator() Validator
- type Scheduler
- type ScopeConfig
- type ScopedContainer
- type ServerOptions
- type Session
- type SessionConfig
- type SignatureConfig
- type Span
- type SpanConfig
- type SpanKind
- type SpanOption
- type StatusCode
- type Task
- type TaskFunc
- type TelemetryConfig
- type Tracer
- type ValidationError
- type ValidationErrors
- type Validator
- type ValidatorFunc
Constants ¶
const DefaultMaxBodyBytes int64 = 1 << 20
const RequestIDHeader = "X-Request-ID"
const Version = "v1.4.0"
Version is the current library version.
Variables ¶
var ErrNotFound = errors.New("route not found")
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
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
LifecycleProvider wraps a provider factory to register lifecycle hooks.
func MustContextValue ¶ added in v1.3.0
MustContextValue extracts a typed request context value by key or returns an unauthorized APIError.
func NewTimerSpan ¶ added in v1.4.0
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 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
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 WebAPIHandler ¶ added in v1.0.1
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
APIError is a standardized error model for HTTP responses.
func BadRequestError ¶ added in v1.1.0
func ConflictError ¶ added in v1.1.0
func ForbiddenError ¶ added in v1.1.0
func InternalError ¶ added in v1.1.0
func NewAPIError ¶ added in v1.1.0
func NotFoundError ¶ added in v1.1.0
func UnauthorizedError ¶ added in v1.1.0
type App ¶
type App struct {
Router *Router
Container *Container
Lifecycle *LifecycleManager
Health *HealthRegistry
}
func (*App) Handler ¶
Handler exposes the application router as an http.Handler. This makes it easy to mount in Gin/Echo/Fiber adapter wrappers.
func (*App) MaxBodyBytes ¶ added in v1.4.0
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
SetMaxBodyBytes sets the maximum request body size used by Context.BindJSON.
func (*App) SetValidator ¶
SetValidator overrides the app/router validator for request DTO validation.
type CORSConfig ¶ added in v1.2.0
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 (*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 (*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) Error ¶ added in v1.0.1
Error returns a standard error envelope: {"success": false, "error": ...}.
func (*Context) InternalError ¶ added in v1.0.1
func (*Context) RecordMetric ¶ added in v1.4.0
RecordMetric records a custom metric attribute on the current span.
func (*Context) Success ¶ added in v1.0.1
Success returns a standard success envelope: {"success": true, "data": ...}.
func (*Context) Unauthorized ¶ added in v1.0.1
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 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
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) EmitAsync ¶ added in v1.4.0
EmitAsync fires an event asynchronously in a goroutine.
func (*EventBus) EmitSync ¶ added in v1.4.0
EmitSync fires an event synchronously, blocking until all handlers complete.
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
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.
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 ¶
func NewHTTPError ¶
type HandlerFunc ¶
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
JWTClaims represents decoded JWT payload.
func JWTClaimsFromContext ¶ added in v1.4.0
JWTClaimsFromContext extracts JWT claims from request context.
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
LifecycleDestroyOnly implements only OnModuleDestroy.
type LifecycleInitOnly ¶ added in v1.4.0
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) SetAttribute ¶ added in v1.4.0
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
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 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 (*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
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) 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
SetMaxBodyBytes sets the maximum request body size used by Context.BindJSON. Values <= 0 disable the framework-level body limit.
func (*Router) SetValidator ¶
SetValidator overrides validation engine used by Context.BindJSON for this router.
func (*Router) Use ¶
func (r *Router) Use(middleware ...Middleware)
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
GetScheduler retrieves the scheduler from context.
func NewScheduler ¶ added in v1.4.0
func NewScheduler() *Scheduler
NewScheduler creates a new task scheduler.
func (*Scheduler) RemoveTask ¶ added in v1.4.0
RemoveTask removes a task by name.
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 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
GetSession retrieves the current session from context.
func (*Session) GenerateID ¶ added in v1.4.0
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
SpanFromContext retrieves the current trace span from context.
type SpanConfig ¶ added in v1.4.0
SpanConfig holds span creation options.
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.
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 ValidationErrors ¶
type ValidationErrors []ValidationError
func (ValidationErrors) Error ¶
func (ve ValidationErrors) Error() string
func (ValidationErrors) Unwrap ¶
func (ve ValidationErrors) Unwrap() error
type Validator ¶
Validator is a pluggable validation engine.
func DefaultValidator ¶
func DefaultValidator() Validator
DefaultValidator returns the process-wide default validator.
type ValidatorFunc ¶
ValidatorFunc adapts a function into a Validator.
func (ValidatorFunc) Validate ¶
func (f ValidatorFunc) Validate(v any) error
Source Files
¶
- auth_helpers.go
- container.go
- context.go
- cron.go
- csrf.go
- decorators.go
- dto.go
- errors.go
- events.go
- generated_registry.go
- health.go
- http_adapters.go
- http_error.go
- idempotency.go
- jwt.go
- jwt_crypto.go
- lifecycle.go
- middleware.go
- middleware_helpers.go
- module.go
- module_middleware.go
- pagination.go
- rate_limit.go
- response_helpers.go
- response_recorder.go
- router.go
- runtime.go
- scope.go
- server.go
- session.go
- signature.go
- standard_middleware.go
- telemetry.go
- upload.go
- validation.go
- version.go
- web_helpers.go