middleware

package
v0.1.6 Latest Latest
Warning

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

Go to latest
Published: Jul 28, 2025 License: MIT Imports: 40 Imported by: 0

Documentation

Overview

Package middleware provides framework-agnostic middleware interfaces and abstractions for the GoForms application. This package defines the core contracts that all middleware implementations must follow, enabling clean architecture principles and framework independence.

Package middleware provides HTTP middleware components.

Package middleware provides middleware orchestration and management.

Package middleware provides framework-agnostic middleware interfaces and abstractions for the GoForms application.

Package middleware provides framework-agnostic middleware interfaces and abstractions for the GoForms application.

Index

Constants

View Source
const (
	// ErrorCodeValidation indicates a validation error.
	ErrorCodeValidation = "VALIDATION_ERROR"

	// ErrorCodeAuthentication indicates an authentication error.
	ErrorCodeAuthentication = "AUTHENTICATION_ERROR"

	// ErrorCodeAuthorization indicates an authorization error.
	ErrorCodeAuthorization = "AUTHORIZATION_ERROR"

	// ErrorCodeRateLimit indicates a rate limiting error.
	ErrorCodeRateLimit = "RATE_LIMIT_ERROR"

	// ErrorCodeTimeout indicates a timeout error.
	ErrorCodeTimeout = "TIMEOUT_ERROR"

	// ErrorCodeInternal indicates an internal middleware error.
	ErrorCodeInternal = "INTERNAL_ERROR"

	// UnknownChainType represents an unknown chain type.
	UnknownChainType = "unknown"
)

ErrorCode represents common middleware error codes.

View Source
const (
	// Default rate limiting values
	DefaultRateLimit = 60
	DefaultBurst     = 10
	DefaultWindow    = time.Minute

	// HTTP Status messages
	RateLimitExceededMsg = "Rate limit exceeded: too many requests from the same form or origin"
	RateLimitDeniedMsg   = "Rate limit exceeded: please try again later"
)

Variables

View Source
var Module = fx.Module("middleware",
	fx.Provide(

		constants.NewPathManager,

		auth.NewMiddleware,

		fx.Annotate(
			func(_ logging.Logger, pathManager *constants.PathManager) *access.Manager {
				config := &access.Config{
					DefaultAccess: access.Authenticated,
					PublicPaths:   pathManager.PublicPaths,
					AdminPaths:    pathManager.AdminPaths,
				}
				rules := generateAccessRules(pathManager)

				return access.NewManager(config, rules)
			},
		),

		fx.Annotate(
			func(
				logger logging.Logger,
				cfg *config.Config,
				lc fx.Lifecycle,
				accessManager *access.Manager,
				pathManager *constants.PathManager,
			) *session.Manager {
				sessionConfig := &session.Config{
					SessionConfig: &cfg.Session,
					Config:        cfg,
					PublicPaths:   pathManager.PublicPaths,
					StaticPaths:   pathManager.StaticPaths,
				}

				return session.NewManager(logger, sessionConfig, lc, accessManager)
			},
		),

		fx.Annotate(
			NewMiddlewareConfig,
			fx.As(new(MiddlewareConfig)),
		),

		fx.Annotate(
			func(logger logging.Logger, config MiddlewareConfig) core.Registry {
				return NewRegistry(logger, config)
			},
			fx.As(new(core.Registry)),
		),

		fx.Annotate(
			func(registry core.Registry, config MiddlewareConfig, logger logging.Logger) core.Orchestrator {
				return NewOrchestrator(registry, config, logger)
			},
			fx.As(new(core.Orchestrator)),
		),

		fx.Annotate(
			NewEchoOrchestratorAdapter,
		),

		fx.Annotate(
			NewMigrationAdapter,
		),

		fx.Annotate(
			func(
				logger logging.Logger,
				cfg *config.Config,
				userService user.Service,
				formService formdomain.Service,
				sessionManager *session.Manager,
				accessManager *access.Manager,
				sanitizer sanitization.ServiceInterface,
			) *Manager {
				return NewManager(&ManagerConfig{
					Logger:         logger,
					Config:         cfg,
					UserService:    userService,
					FormService:    formService,
					SessionManager: sessionManager,
					AccessManager:  accessManager,
					Sanitizer:      sanitizer,
				})
			},
		),
	),

	fx.Invoke(func(
		lc fx.Lifecycle,
		registry core.Registry,
		orchestrator core.Orchestrator,
		logger logging.Logger,
	) {
		lc.Append(fx.Hook{
			OnStart: func(ctx context.Context) error {

				if err := registerAllMiddleware(registry, logger); err != nil {
					return err
				}

				if err := orchestrator.ValidateConfiguration(); err != nil {
					return fmt.Errorf("failed to validate orchestrator configuration: %w", err)
				}

				logger.Info("middleware system initialized successfully")

				return nil
			},
			OnStop: func(ctx context.Context) error {
				logger.Info("middleware system shutting down")

				return nil
			},
		})
	}),
)

Module provides all middleware dependencies

Functions

func ErrorHandlerMiddleware added in v0.1.5

func ErrorHandlerMiddleware(logger logging.Logger, sanitizer sanitization.ServiceInterface) echo.MiddlewareFunc

ErrorHandlerMiddleware returns a middleware that uses the unified error handler

func NewAuthenticationMiddleware added in v0.1.5

func NewAuthenticationMiddleware() core.Middleware

NewAuthenticationMiddleware creates a new authentication middleware

func NewAuthorizationMiddleware added in v0.1.5

func NewAuthorizationMiddleware() core.Middleware

NewAuthorizationMiddleware creates a new authorization middleware

func NewCORSMiddleware added in v0.1.5

func NewCORSMiddleware() core.Middleware

NewCORSMiddleware creates a new CORS middleware

func NewCSRFMiddleware added in v0.1.5

func NewCSRFMiddleware() core.Middleware

NewCSRFMiddleware creates a new CSRF middleware

func NewChain added in v0.1.5

func NewChain(middlewares []core.Middleware) core.Chain

NewChain creates a new chain from a list of middleware.

func NewInputValidationMiddleware added in v0.1.5

func NewInputValidationMiddleware() core.Middleware

NewInputValidationMiddleware creates a new input validation middleware

func NewLoggingMiddleware added in v0.1.5

func NewLoggingMiddleware() core.Middleware

NewLoggingMiddleware creates a new logging middleware

func NewOrchestrator added in v0.1.5

func NewOrchestrator(registry core.Registry, config MiddlewareConfig, logger core.Logger) core.Orchestrator

NewOrchestrator creates a new middleware orchestrator.

func NewRateLimitMiddleware added in v0.1.5

func NewRateLimitMiddleware() core.Middleware

NewRateLimitMiddleware creates a new rate limit middleware

func NewRecoveryMiddleware added in v0.1.5

func NewRecoveryMiddleware() core.Middleware

NewRecoveryMiddleware creates a new recovery middleware

func NewRegistry added in v0.1.5

func NewRegistry(logger core.Logger, config MiddlewareConfig) core.Registry

func NewRequestIDMiddleware added in v0.1.5

func NewRequestIDMiddleware() core.Middleware

NewRequestIDMiddleware creates a new request ID middleware

func NewSecurityHeadersMiddleware added in v0.1.5

func NewSecurityHeadersMiddleware() core.Middleware

NewSecurityHeadersMiddleware creates a new security headers middleware

func NewSessionMiddleware added in v0.1.5

func NewSessionMiddleware() core.Middleware

NewSessionMiddleware creates a new session middleware

func NewTimeoutMiddleware added in v0.1.5

func NewTimeoutMiddleware() core.Middleware

NewTimeoutMiddleware creates a new timeout middleware

func Recovery added in v0.1.5

func Recovery(logger logging.Logger, sanitizer sanitization.ServiceInterface) echo.MiddlewareFunc

Recovery returns a middleware that recovers from panics

Types

type Chain added in v0.1.5

type Chain interface {
	// Process executes the middleware chain for a given request.
	// Returns the final response after all middleware have been processed.
	Process(ctx context.Context, req Request) Response

	// Add appends middleware to the end of the chain.
	// Returns the chain for method chaining.
	Add(middleware ...Middleware) Chain

	// Insert adds middleware at a specific position in the chain.
	// Position 0 inserts at the beginning, position -1 inserts at the end.
	Insert(position int, middleware ...Middleware) Chain

	// Remove removes middleware by name from the chain.
	// Returns true if middleware was found and removed.
	Remove(name string) bool

	// Get returns middleware by name from the chain.
	// Returns nil if middleware is not found.
	Get(name string) Middleware

	// List returns all middleware in the chain in execution order.
	List() []Middleware

	// Clear removes all middleware from the chain.
	Clear() Chain

	// Length returns the number of middleware in the chain.
	Length() int
}

Chain represents a sequence of middleware that can be executed in order. The chain manages the execution flow and ensures proper middleware ordering.

type ChainConfig added in v0.1.5

type ChainConfig struct {
	Enabled         bool
	MiddlewareNames []string
	Paths           []string // Path patterns for this chain
	CustomConfig    map[string]any
}

type ChainType added in v0.1.5

type ChainType int

ChainType represents different types of middleware chains. Each type corresponds to a specific use case or request pattern.

const (
	// ChainTypeDefault represents the default middleware chain for most requests.
	ChainTypeDefault ChainType = iota

	// ChainTypeAPI represents middleware chain for API requests.
	ChainTypeAPI

	// ChainTypeWeb represents middleware chain for web page requests.
	ChainTypeWeb

	// ChainTypeAuth represents middleware chain for authentication endpoints.
	ChainTypeAuth

	// ChainTypeAdmin represents middleware chain for admin-only endpoints.
	ChainTypeAdmin

	// ChainTypePublic represents middleware chain for public endpoints.
	ChainTypePublic

	// ChainTypeStatic represents middleware chain for static asset requests.
	ChainTypeStatic
)

func (ChainType) String added in v0.1.5

func (ct ChainType) String() string

String returns the string representation of the chain type.

type EchoLogger added in v0.1.5

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

EchoLogger implements echo.Logger interface using our custom logger

func (*EchoLogger) Debug added in v0.1.5

func (l *EchoLogger) Debug(i ...any)

Debug logs a message at debug level

func (*EchoLogger) Debugf added in v0.1.5

func (l *EchoLogger) Debugf(format string, args ...any)

Debugf logs a formatted message at debug level

func (*EchoLogger) Debugj added in v0.1.5

func (l *EchoLogger) Debugj(j log.JSON)

Debugj logs a JSON message at debug level

func (*EchoLogger) Error added in v0.1.5

func (l *EchoLogger) Error(i ...any)

Error logs a message at error level

func (*EchoLogger) Errorf added in v0.1.5

func (l *EchoLogger) Errorf(format string, args ...any)

Errorf logs a formatted message at error level

func (*EchoLogger) Errorj added in v0.1.5

func (l *EchoLogger) Errorj(j log.JSON)

Errorj logs a JSON message at error level

func (*EchoLogger) Fatal added in v0.1.5

func (l *EchoLogger) Fatal(i ...any)

Fatal logs a message at fatal level

func (*EchoLogger) Fatalf added in v0.1.5

func (l *EchoLogger) Fatalf(format string, args ...any)

Fatalf logs a formatted message at fatal level

func (*EchoLogger) Fatalj added in v0.1.5

func (l *EchoLogger) Fatalj(j log.JSON)

Fatalj logs a JSON message at fatal level

func (*EchoLogger) Info added in v0.1.5

func (l *EchoLogger) Info(i ...any)

Info logs a message at info level

func (*EchoLogger) Infof added in v0.1.5

func (l *EchoLogger) Infof(format string, args ...any)

Infof logs a formatted message at info level

func (*EchoLogger) Infoj added in v0.1.5

func (l *EchoLogger) Infoj(j log.JSON)

Infoj logs a JSON message at info level

func (*EchoLogger) Level added in v0.1.5

func (l *EchoLogger) Level() log.Lvl

Level returns the current log level

func (*EchoLogger) Output added in v0.1.5

func (l *EchoLogger) Output() io.Writer

Output returns the current log output writer

func (*EchoLogger) Panic added in v0.1.5

func (l *EchoLogger) Panic(i ...any)

Panic logs a message at error level and panics

func (*EchoLogger) Panicf added in v0.1.5

func (l *EchoLogger) Panicf(format string, args ...any)

Panicf logs a formatted message at error level and panics

func (*EchoLogger) Panicj added in v0.1.5

func (l *EchoLogger) Panicj(j log.JSON)

Panicj logs a JSON message at error level and panics

func (*EchoLogger) Prefix added in v0.1.5

func (l *EchoLogger) Prefix() string

Prefix returns the current log prefix

func (*EchoLogger) Print added in v0.1.5

func (l *EchoLogger) Print(i ...any)

Print logs a message at info level

func (*EchoLogger) Printf added in v0.1.5

func (l *EchoLogger) Printf(format string, args ...any)

Printf logs a formatted message at info level

func (*EchoLogger) Printj added in v0.1.5

func (l *EchoLogger) Printj(j log.JSON)

Printj logs a JSON message at info level

func (*EchoLogger) SetHeader added in v0.1.5

func (l *EchoLogger) SetHeader(_ string)

SetHeader sets the log header (no-op as we use our own format)

func (*EchoLogger) SetLevel added in v0.1.5

func (l *EchoLogger) SetLevel(_ log.Lvl)

SetLevel sets the log level (no-op as we use our own configuration)

func (*EchoLogger) SetOutput added in v0.1.5

func (l *EchoLogger) SetOutput(_ io.Writer)

SetOutput sets the log output (no-op as we use our own configuration)

func (*EchoLogger) SetPrefix added in v0.1.5

func (l *EchoLogger) SetPrefix(_ string)

SetPrefix sets the log prefix (no-op as we use our own format)

func (*EchoLogger) Warn added in v0.1.5

func (l *EchoLogger) Warn(i ...any)

Warn logs a message at warn level

func (*EchoLogger) Warnf added in v0.1.5

func (l *EchoLogger) Warnf(format string, args ...any)

Warnf logs a formatted message at warn level

func (*EchoLogger) Warnj added in v0.1.5

func (l *EchoLogger) Warnj(j log.JSON)

Warnj logs a JSON message at warn level

type EchoOrchestratorAdapter added in v0.1.5

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

EchoOrchestratorAdapter adapts the new middleware orchestrator to work with Echo

func NewEchoOrchestratorAdapter added in v0.1.5

func NewEchoOrchestratorAdapter(orchestrator core.Orchestrator, logger logging.Logger) *EchoOrchestratorAdapter

NewEchoOrchestratorAdapter creates a new Echo orchestrator adapter

func (*EchoOrchestratorAdapter) BuildChainForPath added in v0.1.5

func (ea *EchoOrchestratorAdapter) BuildChainForPath(path string) (core.Chain, error)

BuildChainForPath builds a middleware chain for a specific path

func (*EchoOrchestratorAdapter) SetupMiddleware added in v0.1.5

func (ea *EchoOrchestratorAdapter) SetupMiddleware(e *echo.Echo) error

SetupMiddleware sets up middleware chains on the Echo instance

type EchoValidator

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

EchoValidator wraps the infrastructure validator to implement Echo's Validator interface.

func NewValidator

func NewValidator() (*EchoValidator, error)

NewValidator creates a new Echo validator

func (*EchoValidator) Validate

func (v *EchoValidator) Validate(i any) error

Validate implements echo.Validator interface.

type Error added in v0.1.5

type Error struct {
	// Code is the error code for programmatic handling.
	Code string

	// Message is the human-readable error message.
	Message string

	// Middleware is the name of the middleware that generated the error.
	Middleware string

	// Cause is the underlying error that caused this middleware error.
	Cause error

	// Timestamp is when the error occurred.
	Timestamp time.Time
}

Error represents a middleware-specific error. Provides additional context about middleware failures.

func NewError added in v0.1.5

func NewError(code, message, middleware string, cause error) *Error

NewError creates a new middleware error.

func (*Error) Error added in v0.1.5

func (e *Error) Error() string

Error implements the error interface.

func (*Error) Unwrap added in v0.1.5

func (e *Error) Unwrap() error

Unwrap returns the underlying error.

type Handler added in v0.1.5

type Handler func(ctx context.Context, req Request) Response

Handler represents the next handler in the middleware chain. This is a function type that processes a request and returns a response.

type Manager

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

Manager manages all middleware for the application

func NewManager added in v0.1.5

func NewManager(cfg *ManagerConfig) *Manager

func (*Manager) GetSessionManager added in v0.1.5

func (m *Manager) GetSessionManager() *session.Manager

GetSessionManager returns the session manager

func (*Manager) Setup

func (m *Manager) Setup(e *echo.Echo)

Setup registers all middleware with the Echo instance

type ManagerConfig

type ManagerConfig struct {
	Logger         logging.Logger
	Config         *appconfig.Config // Single source of truth
	UserService    user.Service
	FormService    formdomain.Service
	SessionManager *session.Manager
	AccessManager  *access.Manager
	Sanitizer      sanitization.ServiceInterface
}

ManagerConfig contains all dependencies for the middleware manager

func (*ManagerConfig) Validate added in v0.1.5

func (cfg *ManagerConfig) Validate() error

Validate ensures all required configuration is present

type Middleware added in v0.1.5

type Middleware interface {
	// Process handles the middleware logic for a given request.
	// It receives the request context, request data, and the next handler in the chain.
	// Returns a response that can be processed by upstream middleware or handlers.
	Process(ctx context.Context, req Request, next Handler) Response

	// Name returns the unique identifier for this middleware.
	// Used for logging, debugging, and middleware registry management.
	Name() string

	// Priority returns the execution priority of this middleware.
	// Lower numbers indicate higher priority (executed first).
	// Middleware with the same priority are executed in registration order.
	Priority() int
}

Middleware defines the core interface for all middleware components. This interface is framework-agnostic and follows clean architecture principles.

type MiddlewareConfig added in v0.1.5

type MiddlewareConfig interface {
	// IsMiddlewareEnabled checks if a middleware is enabled
	IsMiddlewareEnabled(name string) bool

	// GetMiddlewareConfig returns configuration for a specific middleware
	GetMiddlewareConfig(name string) map[string]any

	// GetChainConfig returns configuration for a specific chain type
	GetChainConfig(chainType core.ChainType) ChainConfig
}

MiddlewareConfig defines the interface for middleware configuration

func NewMiddlewareConfig added in v0.1.5

func NewMiddlewareConfig(cfg *config.Config, logger logging.Logger) MiddlewareConfig

NewMiddlewareConfig creates a new middleware configuration provider

type MigrationAdapter added in v0.1.5

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

MigrationAdapter provides a hybrid approach for gradual migration from old to new middleware system

func NewMigrationAdapter added in v0.1.5

func NewMigrationAdapter(
	orchestrator core.Orchestrator,
	registry core.Registry,
	logger logging.Logger,
) *MigrationAdapter

NewMigrationAdapter creates a new migration adapter

func (*MigrationAdapter) DisableNewSystem added in v0.1.5

func (ma *MigrationAdapter) DisableNewSystem()

DisableNewSystem disables the new middleware system (falls back to old)

func (*MigrationAdapter) EnableNewSystem added in v0.1.5

func (ma *MigrationAdapter) EnableNewSystem()

EnableNewSystem enables the new middleware system

func (*MigrationAdapter) GetMigrationStatus added in v0.1.5

func (ma *MigrationAdapter) GetMigrationStatus() MigrationStatus

GetMigrationStatus returns the current migration status

func (*MigrationAdapter) GetOrchestrator added in v0.1.5

func (ma *MigrationAdapter) GetOrchestrator() core.Orchestrator

GetOrchestrator returns the orchestrator instance

func (*MigrationAdapter) GetRegistry added in v0.1.5

func (ma *MigrationAdapter) GetRegistry() core.Registry

GetRegistry returns the registry instance

func (*MigrationAdapter) IsNewSystemEnabled added in v0.1.5

func (ma *MigrationAdapter) IsNewSystemEnabled() bool

IsNewSystemEnabled returns whether the new system is enabled

func (*MigrationAdapter) MigrateMiddleware added in v0.1.5

func (ma *MigrationAdapter) MigrateMiddleware(middlewareName string) error

MigrateMiddleware migrates a specific middleware from old to new system

func (*MigrationAdapter) RollbackMigration added in v0.1.5

func (ma *MigrationAdapter) RollbackMigration()

RollbackMigration rolls back to the old system

func (*MigrationAdapter) SetupHybridMiddleware added in v0.1.5

func (ma *MigrationAdapter) SetupHybridMiddleware(e *echo.Echo, oldManager *Manager) error

SetupHybridMiddleware sets up middleware using both old and new systems

func (*MigrationAdapter) SetupWithFallback added in v0.1.5

func (ma *MigrationAdapter) SetupWithFallback(e *echo.Echo, oldManager *Manager) error

SetupWithFallback sets up middleware with automatic fallback to old system on error

func (*MigrationAdapter) ValidateMigration added in v0.1.5

func (ma *MigrationAdapter) ValidateMigration() error

ValidateMigration validates that the migration can proceed safely

type MigrationStatus added in v0.1.5

type MigrationStatus struct {
	NewSystemEnabled     bool     `json:"new_system_enabled"`
	RegisteredMiddleware []string `json:"registered_middleware"`
	AvailableChains      []string `json:"available_chains"`
}

MigrationStatus represents the current migration status

type Orchestrator added in v0.1.5

type Orchestrator interface {
	// CreateChain creates a new middleware chain with the specified type.
	// ChainType determines which middleware are included and their order.
	CreateChain(chainType core.ChainType) (core.Chain, error)

	// GetChain retrieves a pre-configured chain by name.
	// Returns nil if chain is not found.
	GetChain(name string) (core.Chain, bool)

	// RegisterChain registers a named chain for later retrieval.
	// Returns an error if chain with the same name already exists.
	RegisterChain(name string, chain core.Chain) error

	// ListChains returns all registered chain names.
	ListChains() []string

	// RemoveChain removes a chain by name.
	// Returns true if chain was found and removed.
	RemoveChain(name string) bool
}

Orchestrator manages the composition and execution of middleware chains. Responsible for creating, configuring, and managing middleware chains based on application requirements and configuration.

type PathChecker added in v0.1.5

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

PathChecker handles path-based logic for middleware

func NewPathChecker added in v0.1.5

func NewPathChecker() *PathChecker

NewPathChecker creates a new path checker with default paths

func (*PathChecker) IsAPIPath added in v0.1.5

func (pc *PathChecker) IsAPIPath(path string) bool

IsAPIPath checks if the path is an API route

func (*PathChecker) IsAuthPath added in v0.1.5

func (pc *PathChecker) IsAuthPath(path string) bool

IsAuthPath checks if the path is an authentication page

func (*PathChecker) IsFormPath added in v0.1.5

func (pc *PathChecker) IsFormPath(path string) bool

IsFormPath checks if the path is a form page

func (*PathChecker) IsHealthPath added in v0.1.5

func (pc *PathChecker) IsHealthPath(path string) bool

IsHealthPath checks if the path is a health check route

func (*PathChecker) IsStaticPath added in v0.1.5

func (pc *PathChecker) IsStaticPath(path string) bool

IsStaticPath checks if the path is a static asset

type Registry added in v0.1.5

type Registry interface {
	// Register adds middleware to the registry with a unique name.
	// Returns an error if middleware with the same name already exists.
	Register(name string, middleware Middleware) error

	// Get retrieves middleware by name from the registry.
	// Returns nil and false if middleware is not found.
	Get(name string) (Middleware, bool)

	// List returns all registered middleware names.
	List() []string

	// Remove removes middleware by name from the registry.
	// Returns true if middleware was found and removed.
	Remove(name string) bool

	// Clear removes all middleware from the registry.
	Clear()

	// Count returns the number of registered middleware.
	Count() int
}

Registry manages middleware registration and discovery. Provides a centralized way to register, retrieve, and manage middleware components.

type Request added in v0.1.5

type Request interface {
	// Method returns the HTTP method (GET, POST, PUT, DELETE, etc.)
	Method() string

	// URL returns the request URL
	URL() *url.URL

	// Path returns the request path
	Path() string

	// Query returns the query parameters
	Query() url.Values

	// Headers returns the request headers
	Headers() http.Header

	// Body returns the request body as an io.Reader
	Body() io.Reader

	// ContentLength returns the length of the request body
	ContentLength() int64

	// ContentType returns the Content-Type header value
	ContentType() string

	// RemoteAddr returns the client's network address
	RemoteAddr() string

	// UserAgent returns the User-Agent header value
	UserAgent() string

	// Referer returns the Referer header value
	Referer() string

	// Host returns the Host header value
	Host() string

	// IsSecure returns true if the request was made over HTTPS
	IsSecure() bool

	// Context returns the request context
	Context() context.Context

	// WithContext returns a new request with the given context
	WithContext(ctx context.Context) Request

	// Get retrieves a value from the request context
	Get(key string) any

	// Set stores a value in the request context
	Set(key string, value any)

	// Param returns a path parameter by name
	Param(name string) string

	// Params returns all path parameters
	Params() map[string]string

	// Cookie returns a cookie by name
	Cookie(name string) (*http.Cookie, error)

	// Cookies returns all cookies
	Cookies() []*http.Cookie

	// FormValue returns a form value by name
	FormValue(name string) string

	// Form returns the parsed form data
	Form() (url.Values, error)

	// MultipartForm returns the parsed multipart form data
	MultipartForm() (*multipart.Form, error)

	// IsAJAX returns true if the request is an AJAX request
	IsAJAX() bool

	// IsWebSocket returns true if the request is a WebSocket upgrade request
	IsWebSocket() bool

	// IsJSON returns true if the request expects JSON response
	IsJSON() bool

	// IsXML returns true if the request expects XML response
	IsXML() bool

	// Accepts returns true if the request accepts the given content type
	Accepts(contentType string) bool

	// AcceptsEncoding returns true if the request accepts the given encoding
	AcceptsEncoding(encoding string) bool

	// AcceptsLanguage returns true if the request accepts the given language
	AcceptsLanguage(language string) bool

	// RealIP returns the real IP address of the client
	RealIP() string

	// ForwardedFor returns the X-Forwarded-For header value
	ForwardedFor() string

	// RequestID returns the request ID if present
	RequestID() string

	// Timestamp returns when the request was received
	Timestamp() time.Time
}

Request represents an HTTP request abstraction that is framework-agnostic. This interface provides access to request data without depending on specific HTTP framework implementations like Echo.

type RequestBuilder added in v0.1.5

type RequestBuilder interface {
	// Method sets the HTTP method
	Method(method string) RequestBuilder

	// URL sets the request URL
	URL(u *url.URL) RequestBuilder

	// Path sets the request path
	Path(path string) RequestBuilder

	// Query sets query parameters
	Query(query url.Values) RequestBuilder

	// AddQuery adds a query parameter
	AddQuery(key, value string) RequestBuilder

	// Header sets a header
	Header(key, value string) RequestBuilder

	// Headers sets multiple headers
	Headers(headers http.Header) RequestBuilder

	// Body sets the request body
	Body(body io.Reader) RequestBuilder

	// ContentType sets the Content-Type header
	ContentType(contentType string) RequestBuilder

	// RemoteAddr sets the client address
	RemoteAddr(addr string) RequestBuilder

	// UserAgent sets the User-Agent header
	UserAgent(userAgent string) RequestBuilder

	// Referer sets the Referer header
	Referer(referer string) RequestBuilder

	// Host sets the Host header
	Host(host string) RequestBuilder

	// Secure sets whether the request is secure
	Secure(secure bool) RequestBuilder

	// Context sets the request context
	Context(ctx context.Context) RequestBuilder

	// Param sets a path parameter
	Param(key, value string) RequestBuilder

	// Params sets all path parameters
	Params(params map[string]string) RequestBuilder

	// Cookie adds a cookie
	Cookie(cookie *http.Cookie) RequestBuilder

	// FormValue sets a form value
	FormValue(key, value string) RequestBuilder

	// AJAX marks the request as AJAX
	AJAX() RequestBuilder

	// WebSocket marks the request as WebSocket
	WebSocket() RequestBuilder

	// JSON marks the request as expecting JSON
	JSON() RequestBuilder

	// XML marks the request as expecting XML
	XML() RequestBuilder

	// RealIP sets the real IP address
	RealIP(ip string) RequestBuilder

	// RequestID sets the request ID
	RequestID(id string) RequestBuilder

	// Timestamp sets the request timestamp
	Timestamp(timestamp time.Time) RequestBuilder

	// Build creates the final Request object
	Build() Request
}

RequestBuilder provides a fluent interface for building Request objects. This is useful for testing and creating mock requests.

func NewRequestBuilder added in v0.1.5

func NewRequestBuilder() RequestBuilder

NewRequestBuilder creates a new RequestBuilder instance.

type Response added in v0.1.5

type Response interface {
	// StatusCode returns the HTTP status code
	StatusCode() int

	// SetStatusCode sets the HTTP status code
	SetStatusCode(code int) Response

	// Headers returns the response headers
	Headers() http.Header

	// SetHeader sets a response header
	SetHeader(key, value string) Response

	// AddHeader adds a response header (doesn't overwrite existing)
	AddHeader(key, value string) Response

	// Body returns the response body as an io.Reader
	Body() io.Reader

	// SetBody sets the response body
	SetBody(body io.Reader) Response

	// BodyBytes returns the response body as bytes
	BodyBytes() []byte

	// SetBodyBytes sets the response body from bytes
	SetBodyBytes(body []byte) Response

	// ContentType returns the Content-Type header value
	ContentType() string

	// SetContentType sets the Content-Type header
	SetContentType(contentType string) Response

	// ContentLength returns the length of the response body
	ContentLength() int64

	// SetContentLength sets the Content-Length header
	SetContentLength(length int64) Response

	// Location returns the Location header value (for redirects)
	Location() string

	// SetLocation sets the Location header (for redirects)
	SetLocation(location string) Response

	// SetCookie adds a cookie to the response
	SetCookie(cookie *http.Cookie) Response

	// Cookies returns all cookies that will be set
	Cookies() []*http.Cookie

	// Error returns the error associated with this response
	Error() error

	// SetError sets the error for this response
	SetError(err error) Response

	// IsError returns true if this response represents an error
	IsError() bool

	// IsRedirect returns true if this response is a redirect
	IsRedirect() bool

	// IsJSON returns true if the response content type is JSON
	IsJSON() bool

	// IsXML returns true if the response content type is XML
	IsXML() bool

	// IsHTML returns true if the response content type is HTML
	IsHTML() bool

	// IsText returns true if the response content type is plain text
	IsText() bool

	// IsBinary returns true if the response content type is binary
	IsBinary() bool

	// Context returns the response context
	Context() context.Context

	// WithContext returns a new response with the given context
	WithContext(ctx context.Context) Response

	// Get retrieves a value from the response context
	Get(key string) any

	// Set stores a value in the response context
	Set(key string, value any)

	// Timestamp returns when the response was created
	Timestamp() time.Time

	// SetTimestamp sets the response timestamp
	SetTimestamp(timestamp time.Time) Response

	// RequestID returns the request ID associated with this response
	RequestID() string

	// SetRequestID sets the request ID for this response
	SetRequestID(id string) Response

	// WriteTo writes the response to the given io.Writer
	WriteTo(io.Writer) (int64, error)

	// Clone creates a copy of this response
	Clone() Response
}

Response represents an HTTP response abstraction that is framework-agnostic. This interface provides access to response data without depending on specific HTTP framework implementations like Echo.

func NewErrorResponse added in v0.1.5

func NewErrorResponse(statusCode int, err error) Response

NewErrorResponse creates a new error response

func NewHTMLResponse added in v0.1.5

func NewHTMLResponse(statusCode int, html string) Response

NewHTMLResponse creates a new HTML response

func NewJSONResponse added in v0.1.5

func NewJSONResponse(data any) Response

NewJSONResponse creates a new JSON response

func NewRedirectResponse added in v0.1.5

func NewRedirectResponse(statusCode int, location string) Response

NewRedirectResponse creates a new redirect response

func NewResponse added in v0.1.5

func NewResponse(statusCode int) Response

NewResponse creates a new response with the given status code

func NewTextResponse added in v0.1.5

func NewTextResponse(statusCode int, text string) Response

NewTextResponse creates a new text response

type ResponseBuilder added in v0.1.5

type ResponseBuilder interface {
	// StatusCode sets the HTTP status code
	StatusCode(code int) ResponseBuilder

	// Header sets a response header
	Header(key, value string) ResponseBuilder

	// Headers sets multiple response headers
	Headers(headers http.Header) ResponseBuilder

	// Body sets the response body
	Body(body io.Reader) ResponseBuilder

	// BodyBytes sets the response body from bytes
	BodyBytes(body []byte) ResponseBuilder

	// ContentType sets the Content-Type header
	ContentType(contentType string) ResponseBuilder

	// ContentLength sets the Content-Length header
	ContentLength(length int64) ResponseBuilder

	// Location sets the Location header (for redirects)
	Location(location string) ResponseBuilder

	// Cookie adds a cookie to the response
	Cookie(cookie *http.Cookie) ResponseBuilder

	// Error sets the error for this response
	Error(err error) ResponseBuilder

	// Context sets the response context
	Context(ctx context.Context) ResponseBuilder

	// Timestamp sets the response timestamp
	Timestamp(timestamp time.Time) ResponseBuilder

	// RequestID sets the request ID for this response
	RequestID(id string) ResponseBuilder

	// JSON marks the response as JSON
	JSON() ResponseBuilder

	// XML marks the response as XML
	XML() ResponseBuilder

	// HTML marks the response as HTML
	HTML() ResponseBuilder

	// Text marks the response as plain text
	Text() ResponseBuilder

	// Build creates the final Response object
	Build() Response
}

ResponseBuilder provides a fluent interface for building Response objects. This is useful for testing and creating mock responses.

func NewResponseBuilder added in v0.1.5

func NewResponseBuilder() ResponseBuilder

NewResponseBuilder creates a new ResponseBuilder instance.

Directories

Path Synopsis
Package access provides access control middleware and utilities for the application.
Package access provides access control middleware and utilities for the application.
Package auth provides authentication middleware and utilities for protecting routes and managing user authentication state.
Package auth provides authentication middleware and utilities for protecting routes and managing user authentication state.
Package chain provides chain building logic for middleware orchestration.
Package chain provides chain building logic for middleware orchestration.
Package context provides middleware utilities for managing request context and user authentication state.
Package context provides middleware utilities for managing request context and user authentication state.
Package core provides the core interfaces and types for middleware functionality.
Package core provides the core interfaces and types for middleware functionality.
Package request provides utilities for HTTP request parsing and validation middleware.
Package request provides utilities for HTTP request parsing and validation middleware.
Package session provides session management middleware and utilities for the application.
Package session provides session management middleware and utilities for the application.

Jump to

Keyboard shortcuts

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