middleware

package
v0.8.1 Latest Latest
Warning

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

Go to latest
Published: Jan 3, 2026 License: MIT Imports: 10 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
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.

View Source
var ErrFailedRecovering = errors.New("failed recovering from unexpected error")

ErrFailedRecovering is an error that's returned when the recover process failed.

View Source
var ErrRecoverUnexpected = errors.New("an unexpected error occurred")

ErrRecoverUnexpected 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

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 HTTP

func HTTP(middleware func(http.Handler) http.Handler) framework.Middleware

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 Provide added in v0.2.0

func Provide(key any, val any) framework.Middleware

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.

Types

type ProvideFunc added in v0.2.0

type ProvideFunc = func(w http.ResponseWriter, r *http.Request) (context.Context, error)

Jump to

Keyboard shortcuts

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