Documentation
¶
Index ¶
- Constants
- Variables
- func CSRF(origins ...string) framework.Middleware
- func CSRFWith(csrf *http.CrossOriginProtection, p problem.Problem) framework.Middleware
- func ErrorHandler(isDev bool) framework.Middleware
- func HTTP(middleware func(http.Handler) http.Handler) framework.Middleware
- func Logger(logger *slog.Logger) framework.Middleware
- func Provide(key any, val any) framework.Middleware
- func ProvideWith(f ProvideFunc) framework.Middleware
- func Recover() framework.Middleware
- func RecoverWith(handler func(value any) error) framework.Middleware
- func Session(driver contract.SessionDriver) framework.Middleware
- func SessionWith(driver contract.SessionDriver, options SessionOptions) framework.Middleware
- type ErrorHandlerOptions
- type ErrorHandlerServeDev
- type ErrorHandlerWriter
- type ProvideFunc
- type SessionOptions
Constants ¶
const DefaultSessionCookie = "cosmos.session"
const DefaultSessionExpirationDelta = 15 * time.Minute
const DefaultSessionTTL = 2 * time.Hour
Variables ¶
var ErrCSRFBlocked = problem.Problem{ Title: "Cross-Origin Request Blocked", Detail: "The request was rejected because its origin or fetch context did not meet security requirements.", Status: http.StatusForbidden, }
ErrCSRFBlocked is the default error returned when a CSRF attack is detected. It contains a structured problem response with appropriate HTTP status and details that can be safely returned to clients without exposing security implementation details.
var ErrRecoverUnexpectedError = errors.New("an unexpected error occurred")
ErrRecoverUnexpectedError is the default error returned when a panic occurs but the recovered value cannot be converted to a meaningful error. This ensures that all panics result in a recoverable error state rather than crashing the application.
Functions ¶
func CSRF ¶
func CSRF(origins ...string) framework.Middleware
CSRF returns a middleware that protects against Cross-Site Request Forgery attacks using Go's built-in http.CrossOriginProtection. It creates a new CSRF protection instance with the specified trusted origins and uses the default ErrCSRFBlocked error for rejected requests.
Parameters:
- origins: A list of trusted origin URLs that are allowed to make cross-origin requests
Returns a middleware function that can be applied to routes or route groups.
func CSRFWith ¶
func CSRFWith(csrf *http.CrossOriginProtection, p problem.Problem) framework.Middleware
CSRFWith creates a CSRF protection middleware using a custom CrossOriginProtection instance and a custom error response. This provides full control over the CSRF configuration and error handling behavior.
Parameters:
- csrf: A configured CrossOriginProtection instance with desired settings
- p: The problem.Problem to return when CSRF validation fails
Returns a middleware function that validates requests and returns the custom error on failure.
func ErrorHandler ¶
func ErrorHandler(isDev bool) framework.Middleware
ErrorHandler creates middleware that provides centralized error handling for Cosmos applications. It captures HTTP status codes, logs server errors (5xx status codes), and provides different error handling strategies based on the environment and error type.
The middleware supports:
- Development mode with enhanced error details via ErrorHandlerDevHandler
- Standard http.Handler error types for custom error responses
- Fallback to basic error responses for unhandled error types
Parameters:
- isDev: Determines if the error handler is in development mode.
Returns a middleware function that handles errors from downstream handlers.
func HTTP ¶
HTTP creates an adapter that allows standard Go HTTP middleware to be used with Cosmos handlers. This enables integration with existing HTTP middleware libraries and patterns while preserving Cosmos's error-returning handler semantics.
The adapter works by:
- Converting the Cosmos handler chain into a standard http.Handler
- Applying the provided HTTP middleware to the converted handler
- Capturing any errors returned by the Cosmos handlers
- Returning those errors through the Cosmos middleware chain
This allows you to use third-party HTTP middleware (CORS, authentication, etc.) without losing the error handling benefits of Cosmos handlers.
Parameters:
- middleware: A standard HTTP middleware function that takes and returns http.Handler
Returns a Cosmos middleware that integrates the HTTP middleware into the handler chain.
Example:
app.Use(HTTP(someThirdPartyMiddleware))
func Logger ¶ added in v0.2.0
func Logger(logger *slog.Logger) framework.Middleware
Logger creates middleware that provides comprehensive request logging for Cosmos applications. It captures HTTP status codes, logs requests that result in errors or server errors (5xx status codes), and provides structured logging with contextual information about each request.
The middleware logs the following information for failed requests:
- HTTP method (GET, POST, etc.)
- Full request URL
- HTTP status code returned
- Any error returned by the handler
Logging is triggered when:
- A handler returns an error (regardless of status code)
- The response has a 5xx server error status code
The middleware uses structured logging with slog for consistent log formatting and includes request context for distributed tracing compatibility.
Parameters:
- logger: The slog.Logger instance to use for logging. If nil, a discard logger is used to prevent panics while maintaining functionality.
Returns a middleware function that wraps handlers with request logging.
Example usage:
logger := slog.New(slog.NewJSONHandler(os.Stdout, nil)) app.Use(middleware.Logger(logger))
func ProvideWith ¶ added in v0.2.0
func ProvideWith(f ProvideFunc) framework.Middleware
func Recover ¶
func Recover() framework.Middleware
Recover creates middleware that recovers from panics in HTTP handlers and converts them to errors using the default recovery handler. This prevents panics from crashing the entire application and allows them to be handled through the normal error handling middleware chain.
The default handler converts common panic types (errors, strings, fmt.Stringers) into appropriate error values. For unknown types, it returns ErrRecoverUnexpectedError joined with a formatted representation of the panic value.
Returns a middleware function that catches panics and converts them to errors.
func RecoverWith ¶
func RecoverWith(handler func(value any) error) framework.Middleware
RecoverWith creates middleware that recovers from panics using a custom recovery handler function. This allows applications to implement custom panic handling logic, such as specialized logging, error formatting, or panic value processing.
The custom handler receives the raw panic value and must return an error that will be passed through the normal error handling chain.
Parameters:
- handler: A function that converts panic values to errors
Returns a middleware function that catches panics and processes them with the custom handler.
func Session ¶ added in v0.5.0
func Session(driver contract.SessionDriver) framework.Middleware
func SessionWith ¶ added in v0.5.0
func SessionWith(driver contract.SessionDriver, options SessionOptions) framework.Middleware
Types ¶
type ErrorHandlerOptions ¶
type ErrorHandlerOptions struct {
// Logger is used to log errors with status codes >= 500. If nil,
// a discard logger will be used to prevent panics.
Logger *slog.Logger
// IsDev enables development mode, which uses ErrorHandlerDevHandler
// when available to provide enhanced error information.
IsDev bool
}
ErrorHandlerOptions configures the behavior of the error handling middleware.
type ErrorHandlerServeDev ¶ added in v0.2.0
type ErrorHandlerServeDev interface {
// ServeHTTPDev handles the error response in development mode,
// typically providing additional debugging information.
ServeHTTPDev(w http.ResponseWriter, r *http.Request)
}
ErrorHandlerServeDev defines an interface for errors that can provide enhanced development-time error responses. When running in development mode, errors implementing this interface will use their ServeHTTPDev method instead of the standard error handling, allowing for richer debug information.
type ErrorHandlerWriter ¶
type ErrorHandlerWriter interface {
http.ResponseWriter
framework.HTTPStatus
}
ErrorHandlerWriter extends http.ResponseWriter with the ability to retrieve the HTTP status code that was written to the response. This interface is used by the error handling middleware to make status-based decisions.