middlewares

package
v1.6.0 Latest Latest
Warning

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

Go to latest
Published: Mar 21, 2026 License: MIT Imports: 20 Imported by: 0

Documentation

Index

Constants

View Source
const RequestIDKey = chimiddleware.RequestIDKey

RequestIDKey is the key used to store the request ID in the context. This matches Chi's RequestIDKey for consistency.

Variables

This section is empty.

Functions

func BasicAuthenticationMiddleware added in v0.10.0

func BasicAuthenticationMiddleware(username string, password string) rtr.MiddlewareInterface

BasicAuthenticationMiddleware creates a new middleware that enforces HTTP Basic Authentication using the provided username and password.

func CORSMiddleware added in v0.10.0

func CORSMiddleware(opts cors.Options) rtr.MiddlewareInterface

CORSMiddleware returns a middleware that handles CORS requests. It's a thin wrapper around go-chi/cors middleware. By default, it allows all origins, methods, and headers. Use the options to customize the CORS behavior.

func CleanPathMiddleware added in v0.8.0

func CleanPathMiddleware() rtr.MiddlewareInterface

CleanPathMiddleware creates a new middleware that cleans up double slashes in URL paths. For example, it converts "/users//1" or "//users////1" to "/users/1". This should typically be added early in the middleware chain.

func CompressMiddleware added in v0.10.0

func CompressMiddleware(level int, types ...string) rtr.MiddlewareInterface

CompressMiddleware returns a middleware that compresses HTTP responses. It supports gzip, deflate, and brotli compression based on the client's Accept-Encoding header. This is a thin wrapper around klauspost/compress/gzhttp's Transport.

func DefaultCORSMiddleware added in v0.10.0

func DefaultCORSMiddleware() rtr.MiddlewareInterface

DefaultCORSMiddleware returns a CORS middleware with sensible defaults: - Allow all origins - Allow common HTTP methods - Allow common headers - Allow credentials - Max age: 300 (5 minutes)

func GetHead added in v0.8.0

func GetHead() rtr.MiddlewareInterface

GetHead creates a middleware that automatically routes undefined HEAD requests to GET handlers. This is useful for automatically handling HEAD requests without requiring explicit HEAD handlers.

By using this middleware, you are in compliance with the HTTP/1.1 spec (RFC 2616), which states that servers MUST support the HEAD method for any URI that returns a response body for a GET request.

Additionally, this middleware provides a performance benefit by saving clients the overhead of downloading the full response body when they only need metadata.

This is a common web practice, and many web frameworks and servers (like Express.js, Django, etc.) provide this functionality out of the box. It also saves developers from having to implement HEAD handlers separately for every route.

Usage:

router := rtr.NewRouter()
router.AddRoute(rtr.NewRoute().
  SetMethod("GET").
  SetPath("/test").
  SetHandler(func(w http.ResponseWriter, r *http.Request) {
    w.WriteHeader(http.StatusOK)
  }).
  AddMiddleware(middlewares.GetHead()))

Parameters:

  • next: The next handler in the middleware chain.

Returns:

  • A middleware that automatically routes undefined HEAD requests to GET handlers.

func GetRequestID added in v0.10.0

func GetRequestID(ctx context.Context) string

GetRequestID retrieves the request ID from the context. Returns an empty string if no request ID is found.

func HeartbeatMiddleware added in v0.10.0

func HeartbeatMiddleware(endpoint string) rtr.MiddlewareInterface

HeartbeatMiddleware endpoint middleware useful to setting up a path like `/ping` that load balancers or uptime testing external services can make a request before hitting any routes. It's also convenient to place this above ACL middlewares as well.

func JailBotsMiddleware added in v1.6.0

func JailBotsMiddleware(config JailBotsConfig) rtr.MiddlewareInterface

func LoggerMiddleware added in v0.10.0

func LoggerMiddleware() rtr.MiddlewareInterface

LoggerMiddleware returns a middleware that logs the start and end of each request, along with some useful data about what was requested, what the status code was, and how long it took. This is a thin wrapper around Chi's Logger middleware.

func NakedDomainToWwwMiddleware added in v1.3.0

func NakedDomainToWwwMiddleware(hostExcludes []string) rtr.MiddlewareInterface

NakedDomainToWwwMiddleware redirects naked domains to the www subdomain. hostExcludes allows bypassing the redirect for specific hosts (e.g., localhost).

func NewHTTPSRedirectMiddleware added in v1.5.0

func NewHTTPSRedirectMiddleware(config *HTTPSRedirectConfig) rtr.MiddlewareInterface

NewHTTPSRedirectMiddleware creates middleware that redirects HTTP requests to HTTPS

func NewSecurityHeadersMiddleware added in v1.5.0

func NewSecurityHeadersMiddleware(config *SecurityHeadersConfig) rtr.MiddlewareInterface

NewSecurityHeadersMiddleware creates middleware that sets security headers

func ProfilerMiddleware added in v0.10.0

func ProfilerMiddleware() rtr.MiddlewareInterface

ProfilerMiddleware returns a middleware that serves the Go pprof profiler. It's a thin wrapper around Chi's Profiler middleware. The profiler will be available at the specified path (e.g., "/debug/pprof"). Make sure to only enable this in development environments as it exposes sensitive debugging information.

func RateLimitByIPMiddleware added in v0.10.0

func RateLimitByIPMiddleware(maxRequests int, seconds int) rtr.MiddlewareInterface

func RealIPMiddleware added in v0.10.0

func RealIPMiddleware() rtr.MiddlewareInterface

RealIPMiddleware returns a middleware that sets the client's real IP address in the request context. It uses Chi's RealIP middleware internally.

func RecoveryMiddleware

func RecoveryMiddleware() rtr.MiddlewareInterface

RecoveryMiddleware creates a new middleware that recovers from panics. It logs the panic details and returns a 500 Internal Server Error response. This should typically be added as one of the first middlewares in the chain.

func RedirectSlashesMiddleware added in v0.10.0

func RedirectSlashesMiddleware() rtr.MiddlewareInterface

func RequestIDMiddleware added in v0.10.0

func RequestIDMiddleware() rtr.MiddlewareInterface

RequestIDMiddleware returns a middleware that adds a unique request ID to the context and response headers. The request ID can be retrieved using GetRequestID(ctx). This is a thin wrapper around Chi's RequestID middleware for consistency with the project.

func ThrottleMiddleware added in v0.10.0

func ThrottleMiddleware(requests int, window time.Duration) rtr.MiddlewareInterface

ThrottleMiddleware returns a middleware that limits the number of requests per time window. It uses the client's IP address to track request counts. This is a thin wrapper around go-chi/httprate's Limit function.

func TimeoutMiddleware added in v0.10.0

func TimeoutMiddleware(timeout time.Duration) rtr.MiddlewareInterface

TimeoutMiddleware returns a middleware that adds a timeout to the request context. If the request takes longer than the specified duration, it will be canceled. This is a thin wrapper around Chi's Timeout middleware.

func WwwToNakedDomainMiddleware added in v1.3.0

func WwwToNakedDomainMiddleware() rtr.MiddlewareInterface

WwwToNakedDomainMiddleware redirects requests from the www subdomain to the naked domain.

Types

type CSPConfig added in v1.5.0

type CSPConfig struct {
	Enabled                 bool
	DefaultSrc              []string
	ScriptSrc               []string
	StyleSrc                []string
	FontSrc                 []string
	ImgSrc                  []string
	ConnectSrc              []string
	MediaSrc                []string
	ObjectSrc               []string
	ChildSrc                []string
	WorkerSrc               []string
	ManifestSrc             []string
	UpgradeInsecureRequests bool
}

CSPConfig configures Content Security Policy

type FrameOptionsConfig added in v1.5.0

type FrameOptionsConfig struct {
	Enabled bool
	Option  string // "DENY", "SAMEORIGIN", or "ALLOW-FROM uri"
}

FrameOptionsConfig configures X-Frame-Options

type HSTSConfig added in v1.5.0

type HSTSConfig struct {
	Enabled           bool
	MaxAge            int
	IncludeSubDomains bool
	Preload           bool
}

HSTSConfig configures HTTP Strict Transport Security

type HTTPSRedirectConfig added in v1.5.0

type HTTPSRedirectConfig struct {
	// SkipLocalhost skips HTTPS redirect for localhost and local development
	SkipLocalhost bool
	// TrustedProxies contains list of trusted proxy IPs for X-Forwarded-Proto checking
	TrustedProxies []string
	// CustomSkipFunc allows custom logic to skip HTTPS redirect
	CustomSkipFunc func(r *http.Request) bool
}

HTTPSRedirectConfig provides configuration for HTTPS redirect middleware

func DefaultHTTPSRedirectConfig added in v1.5.0

func DefaultHTTPSRedirectConfig() *HTTPSRedirectConfig

DefaultHTTPSRedirectConfig returns a default configuration

type JailBotsConfig added in v1.6.0

type JailBotsConfig struct {
	// Exclude filters items out of the internal URI blacklist lists used by
	// isJailable (e.g., if "wp" is in the blacklist but you want to allow it,
	// add "wp" here). Matches are compared literally against the blacklist
	// entries, not against request paths.
	Exclude []string

	// ExcludePaths defines request path patterns that must bypass the jail logic.
	// Supported patterns:
	//  - With a trailing '*': treated as a simple prefix match, e.g. "/blog*" matches
	//    "/blog", "/blog/", and any subpaths like "/blog/post".
	//  - Without '*': segment-aware; matches exactly the path (e.g. "/blog") or any
	//    subpath starting with that segment (e.g. "/blog/..."), but NOT lookalikes
	//    like "/blogger".
	ExcludePaths []string
}

JailBotsConfig defines configuration for jail bots middleware

type SecurityHeadersConfig added in v1.5.0

type SecurityHeadersConfig struct {
	// Content Security Policy configuration
	CSP *CSPConfig
	// HSTS configuration
	HSTS *HSTSConfig
	// Frame options configuration
	FrameOptions *FrameOptionsConfig
	// Content type options
	ContentTypeNosniff bool
	// XSS protection
	XSSProtection *XSSProtectionConfig
	// Referrer policy
	ReferrerPolicy string
	// Permissions policy
	PermissionsPolicy map[string][]string
	// Custom headers allows adding custom security headers
	CustomHeaders map[string]string
}

SecurityHeadersConfig provides configuration for security headers middleware

func DefaultSecurityHeadersConfig added in v1.5.0

func DefaultSecurityHeadersConfig() *SecurityHeadersConfig

DefaultSecurityHeadersConfig returns a secure default configuration

type XSSProtectionConfig added in v1.5.0

type XSSProtectionConfig struct {
	Enabled bool
	Mode    string // "block" or empty
}

XSSProtectionConfig configures X-XSS-Protection

Jump to

Keyboard shortcuts

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