middleware

package
v0.0.20 Latest Latest
Warning

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

Go to latest
Published: Dec 16, 2024 License: Apache-2.0 Imports: 12 Imported by: 0

Documentation

Overview

Package middleware provides HTTP middleware components for the route package.

Each middleware is designed to be configurable while providing secure defaults. Most middleware can be used with default options by passing nil as the options function.

For detailed documentation and examples, see the documentation for individual middleware types.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CORS

func CORS(optsFunc func(opts *CORSOptions)) func(http.Handler) http.Handler

CORS provides Cross-Origin Resource Sharing middleware For more information, see https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

Example:

router.Use(middleware.CORS(func(opts *middleware.CORSOptions) {
	opts.AllowOrigins = []string{"https://example.com"}
}))

func ContentSecurityPolicy

func ContentSecurityPolicy(optsFunc func(opts *ContentSecurityPolicyOptions)) route.Middleware

ContentSecurityPolicy sets the Content-Security-Policy header to protect against XSS attacks. For more information, see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy

Example:

r.Use(middleware.ContentSecurityPolicy(func(opts *middleware.ContentSecurityPolicyOptions) {
	opts.DefaultSrc = "'self'"
	opts.ImgSrc = "'self' https://example.com"
}))

func Logger

func Logger(l *slog.Logger, level slog.Level) func(http.Handler) http.Handler

Logger returns middleware that logs all requests using slog

Example:

router.Use(middleware.Logger(logger, slog.Info))

This will log all requests using the provided slog.Logger at the Info level.

func PreventCSRF

func PreventCSRF(opts PreventCSRFOptions) route.Middleware

PreventCSRF prevents CSRF attacks by setting a CSRF cookie.

func Recovery

func Recovery(logger *slog.Logger, handler ErrorHandler) func(http.Handler) http.Handler

Recovery returns middleware that recovers from panics and calls the optional error handler If no error handler is provided, a default error response is sent

Example:

router.Use(middleware.Recovery(logger, func(w http.ResponseWriter, r *http.Request, err any) {
	http.Error(w, "Internal Server Error", http.StatusInternalServerError)
}))

func SecurityHeaders

func SecurityHeaders(optsFunc func(*SecurityHeadersOptions)) route.Middleware

SecurityHeaders middleware sets security headers with configurable options See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers for more information

Example (defaults):

router.Use(middleware.SecurityHeaders(nil))

Example (custom):

router.Use(middleware.SecurityHeaders(func(opts *middleware.SecurityHeadersOptions) {
	opts.ReferrerPolicy = "no-referrer"
	opts.ContentTypeOptions = "nosniff"
	opts.FrameOptions = "sameorigin"
	opts.StrictTransportSecurity = "max-age=63072000; includeSubDomains"
	opts.Additional["X-Custom-Header"] = "custom-value"
}))

func Timeout

func Timeout(timeout time.Duration) func(http.Handler) http.Handler

Timeout returns middleware that cancels requests after a timeout

Example:

router.Use(middleware.Timeout(5 * time.Second))

Types

type CORSOptions

type CORSOptions struct {
	// AllowOrigins is a list of origins a cross-domain request can be executed from.
	// If the special "*" value is present in the list, all origins will be allowed.
	// Default value is []string{"*"}
	AllowOrigins []string

	// AllowMethods is a list of methods the client is allowed to use with
	// cross-domain requests. Default value is simple methods (GET, POST, HEAD).
	AllowMethods []string

	// AllowHeaders is list of non simple headers the client is allowed to use with
	// cross-domain requests. Default value is [].
	AllowHeaders []string

	// ExposeHeaders indicates which headers are safe to expose to the API of a
	// CORS response. Default value is [].
	ExposeHeaders []string

	// AllowCredentials indicates whether the request can include user credentials like
	// cookies, HTTP authentication or client side SSL certificates.
	// Default value is false.
	AllowCredentials bool

	// MaxAge indicates how long (in seconds) the results of a preflight request
	// can be cached. Default value is 12 hours.
	MaxAge time.Duration

	// OptionsSuccessStatus provides a status code to use for successful OPTIONS requests.
	// Default value is 204.
	OptionsSuccessStatus int
}

CORSOptions contains the configuration for CORS middleware

type ContentSecurityPolicyOptions

type ContentSecurityPolicyOptions struct {
	// ChildSrc sets the sources that can be used in child contexts.
	ChildSrc string
	// ConnectSrc sets the sources that can be used for WebSockets, EventSource, and other interfaces.
	ConnectSrc string
	// DefaultSrc sets the default sources for fetch, worker, frame, embed, and object.
	DefaultSrc string
	// FontSrc sets the sources for fonts.
	FontSrc string
	// FormAction sets the sources that can be used as the target of form submissions.
	FrameSrc string
	// ImgSrc sets the sources for images.
	ImgSrc string
	// ManifestSrc sets the sources for web app manifests.
	ManifestSrc string
	// MediaSrc sets the sources for audio and video.
	MediaSrc string
	// ObjectSrc sets the sources for objects.
	ObjectSrc string
	// ScriptSrc sets the sources for scripts.
	ScriptSrc string
	// ScriptSrcElem sets the sources for inline scripts.
	ScriptSrcElem string
	// ScriptSrcAttr sets the sources for script attributes.
	ScriptSrcAttr string
	// StyleSrc sets the sources for stylesheets.
	StyleSrc string
	// StyleSrcElem sets the sources for inline styles.
	StyleSrcElem string
	// StyleSrcAttr sets the sources for style attributes.
	StyleSrcAttr string
	// WorkerSrc sets the sources for workers.
	WorkerSrc string
	// BaseURI sets the sources for the document base URL.
	BaseURI string
	// Sandbox sets the restrictions for content in an iframe.
	Sandbox string
	// FormAction sets the sources that can be used as the target of form submissions.
	FormAction string
	// FrameAncestors sets the sources that can embed the page in a frame.
	FrameAncestors string
	// ReportURI sets the URI to send reports of policy violations.
	ReportTo string
}

ContentSecurityPolicyOptions contains the options for the Content-Security-Policy header.

type ErrorHandler

type ErrorHandler func(w http.ResponseWriter, r *http.Request, err error)

ErrorHandler is a function that handles errors during request processing

type PreventCSRFOptions

type PreventCSRFOptions struct {
	HTTPOnly bool
	Path     string
	MaxAge   int
	SameSite string
	Secure   bool
}

PreventCSRFOptions provides options for PreventCSRF

type SecurityHeadersOptions

type SecurityHeadersOptions struct {
	// ReferrerPolicy controls the Referrer-Policy header.
	// Default is "origin-when-cross-origin"
	ReferrerPolicy string

	// ContentTypeOptions controls the X-Content-Type-Options header.
	// Default is "nosniff"
	ContentTypeOptions string

	// FrameOptions controls the X-Frame-Options header.
	// Default is "deny"
	FrameOptions string

	// StrictTransportSecurity controls the Strict-Transport-Security header.
	// Empty string means the header won't be set
	StrictTransportSecurity string

	// Additional headers to set
	Additional map[string]string
}

SecurityHeadersOptions contains configuration for security headers

Jump to

Keyboard shortcuts

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