middleware

package
v0.0.0-...-a782910 Latest Latest
Warning

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

Go to latest
Published: Dec 24, 2024 License: MIT Imports: 9 Imported by: 0

Documentation

Overview

Package middleware provides middlewares for handling common web application requirements. This package includes middleware for handling Cross-Origin Resource Sharing (CORS).

Package middleware provides middlewares for handling common web application requirements.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CORS

func CORS() puff.Middleware

CORS returns a CORS middleware with the default configuration.

func CORSWithConfig

func CORSWithConfig(c CORSConfig) puff.Middleware

CORSWithConfig returns a CORS middleware with the specified configuration.

func CSRF

func CSRF() puff.Middleware

CSRF middleware automatically injects a cookie with a unique token and requires the request to provide the csrf token in the response header. If the CSRF Token is not present in the response header, the request is rejected with a 403 error. The function returns a middleware with the default configuration.

func CSRFWithConfig

func CSRFWithConfig(config *CSRFMiddlewareConfig) puff.Middleware

CSRFWithConfig returns a CSRF middleware with your configuration.

func DefaultSkipper

func DefaultSkipper(c *puff.Context) bool

DefaultSkipper can be set on a middleware config to never skip the middleware

func Logging

func Logging() puff.Middleware

Logging returns a Logging middleware with the default configuration. BUG(Puff): Default Logging Middleware is not context aware and therefore cannot format logs based on the defined logger config.

func LoggingWithConfig

func LoggingWithConfig(tc LoggingConfig) puff.Middleware

LoggingWithConfig returns a Logging middleware with the specified configuration.

func Panic

func Panic() puff.Middleware

Panic middleware returns a middleware with the default configuration.

func PanicWithConfig

func PanicWithConfig(pc PanicConfig) puff.Middleware

PanicWithConfig returns a middleware with your configuration.

func Tracing

func Tracing() puff.Middleware

Tracing middleware provides the ability to automatically trace every route with a request id. The function returns a middleware with the default tracing config.

func TracingWithConfig

func TracingWithConfig(tc TracingConfig) puff.Middleware

TracingWithConfig returns a tracing middleware with the config given.

Types

type CORSConfig

type CORSConfig struct {
	// Skip allows skipping the middleware for specific requests.
	// The function receives the request context and should return true if the middleware should be skipped.
	Skip func(*puff.Context) bool

	// AllowedOrigin specifies the allowed origin for CORS.
	AllowedOrigin string

	// AllowedMethods specifies the allowed HTTP methods for CORS.
	AllowedMethods []string

	// AllowedHeaders specifies the allowed HTTP headers for CORS.
	AllowedHeaders []string
}

CORSConfig defines the configuration for the CORS middleware.

var DefaultCORSConfig CORSConfig = CORSConfig{
	AllowedOrigin: "*",
	AllowedMethods: []string{
		http.MethodGet,
		http.MethodHead,
		http.MethodConnect,
		http.MethodOptions,
		http.MethodTrace,
		http.MethodPut,
		http.MethodPatch,
		http.MethodPost,
		http.MethodDelete,
	},
	AllowedHeaders: []string{"Content-Type", "Authorization", "Origin"},
	Skip:           DefaultSkipper,
}

DefaultCORSConfig provides the default configuration for CORS middleware.

type CSRFMiddlewareConfig

type CSRFMiddlewareConfig struct {
	// Skip allows skipping the middleware for specific requests.
	// The function receives the request context and should return true if the middleware should be skipped.
	Skip func(*puff.Context) bool
	// CookieLength specifies the length of the token.
	CookieLength int
	// MaxAge specifies the maximum length for the CSRF cookie.
	MaxAge int
	// ExpectedHeader declares what request header CSRF should be looking for when verifying.
	ExpectedHeader string
	// ProtectedMethods declares what http methods CSRF should secure.
	ProtectedMethods []string
}

CSRFMiddlewareConfig is a struct to configure the CSRF middleware.

var DefaultCSRFMiddleware *CSRFMiddlewareConfig = &CSRFMiddlewareConfig{
	CookieLength:     32,
	MaxAge:           31449600,
	ExpectedHeader:   "X-CSRFMiddlewareToken",
	ProtectedMethods: []string{},
	Skip:             DefaultSkipper,
}

DefaultCSRFMiddleware is a CSRFMiddlewareConfig with specified default values.

type LoggingConfig

type LoggingConfig struct {
	// Skip allows skipping the middleware for specific requests.
	// The function receives the request context and should return true if the middleware should be skipped.
	Skip func(*puff.Context) bool
	// LoggingFunction is a definable function for customizing the log on an http request.
	// Should theoretically call a method deriving from slog.Log
	LoggingFunction func(ctx puff.Context, startTime time.Time)
}

LoggingConfig defines the configuration for the Logging middleware.

var DefaultLoggingConfig LoggingConfig = LoggingConfig{
	LoggingFunction: func(ctx puff.Context, startTime time.Time) {

		processingTime := time.Since(startTime).String()
		sc := ctx.GetStatusCode()
		var statusColor string
		switch {
		case sc >= 500:
			statusColor = color.Colorize(strconv.Itoa(sc), color.FgBrightRed)
		case sc >= 400:
			statusColor = color.Colorize(strconv.Itoa(sc), color.BgBrightYellow)
		case sc >= 300:
			statusColor = color.Colorize(strconv.Itoa(sc), color.FgBrightCyan)
		default:
			statusColor = color.Colorize(strconv.Itoa(sc), color.FgBrightGreen)
		}

		slog.Info(
			fmt.Sprintf("%s %s| %s | %s | %s ",
				statusColor,
				fmt.Sprintf("%s %s", ctx.Request.Method, ctx.Request.URL.String()),
				processingTime,
				ctx.GetRequestID(),
				ctx.ClientIP(),
			),
		)
	},
	Skip: DefaultSkipper,
}

type PanicConfig

type PanicConfig struct {
	// Skip allows skipping the middleware for specific requests.
	// The function receives the request context and should return true if the middleware should be skipped.
	Skip func(*puff.Context) bool
	// FormatErrorResponse provides a function that recieves the context of the route that resulted in a panic and the error.
	// It should provide a response that can be sent back to the user.
	FormatErrorResponse func(c puff.Context, err any) puff.Response
}

PanicConfig provides a struct to configure the Panic middleware.

var DefaultPanicConfig PanicConfig = PanicConfig{
	FormatErrorResponse: func(c puff.Context, err any) puff.Response {
		errorID := puff.RandomNanoID()
		slog.Error("Panic During Execution", slog.String("ERROR ID", errorID), slog.Any("Error", err))
		errorMsg := fmt.Sprintf("There was a panic during the execution recovered by the panic handling middleware. Error ID: %s", errorID)
		return puff.JSONResponse{StatusCode: http.StatusInternalServerError, Content: map[string]any{"error": errorMsg, "Request-ID": c.GetRequestID()}}
	},
	Skip: DefaultSkipper,
}

DefaultCSRFMiddleware is a PanicConfig with specified default values.

type TracingConfig

type TracingConfig struct {
	// Skip allows skipping the middleware for specific requests.
	// The function receives the request context and should return true if the middleware should be skipped.
	Skip func(*puff.Context) bool
	//TracerName is the name of the response header in which Request ID will be present.
	TracerName string
	// IDGenerator is a function that must return a string to generate the Request ID.
	IDGenerator func() string
}

TracingConfig is a struct to configure the tracing middleware.

var DefaultTracingConfig TracingConfig = TracingConfig{
	TracerName:  "X-Request-ID",
	IDGenerator: uuid.NewString,
	Skip:        DefaultSkipper,
}

DefaultTracingConfig is a TracingConfig with specified default values.

Notes

Bugs

  • Default Logging Middleware is not context aware and therefore cannot format logs based on the defined logger config.

Jump to

Keyboard shortcuts

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