Documentation
¶
Index ¶
- Variables
- func AuthMiddleware(config AuthMiddlewareConfig) rtr.MiddlewareInterface
- func BasicAuthenticationMiddleware(username string, password string) rtr.MiddlewareInterface
- func CORSMiddleware(opts CORSOptions) rtr.MiddlewareInterface
- func CleanPathMiddleware() rtr.MiddlewareInterface
- func CompressMiddleware(level int, types ...string) rtr.MiddlewareInterface
- func DefaultCORSMiddleware() rtr.MiddlewareInterface
- func GetHead() rtr.MiddlewareInterface
- func GetRequestID(ctx context.Context) string
- func HeartbeatMiddleware(endpoint string) rtr.MiddlewareInterface
- func JailBotsMiddleware(config JailBotsConfig) rtr.MiddlewareInterface
- func LoggerMiddleware() rtr.MiddlewareInterface
- func NakedDomainToWwwMiddleware(hostExcludes []string) rtr.MiddlewareInterface
- func NewHTTPSRedirectMiddleware(config *HTTPSRedirectConfig) rtr.MiddlewareInterface
- func NewSecurityHeadersMiddleware(config *SecurityHeadersConfig) rtr.MiddlewareInterface
- func ProfilerMiddleware() rtr.MiddlewareInterface
- func RateLimitByIPMiddleware(maxRequests int, seconds int) rtr.MiddlewareInterface
- func RealIPMiddleware() rtr.MiddlewareInterface
- func RecoveryMiddleware() rtr.MiddlewareInterface
- func RedirectSlashesMiddleware() rtr.MiddlewareInterface
- func RequestIDMiddleware() rtr.MiddlewareInterface
- func ThrottleMiddleware(requests int, window time.Duration) rtr.MiddlewareInterface
- func TimeoutMiddleware(timeout time.Duration) rtr.MiddlewareInterface
- func UserMiddleware(config UserMiddlewareConfig) rtr.MiddlewareInterface
- func WwwToNakedDomainMiddleware() rtr.MiddlewareInterface
- type AuthLogger
- type AuthMiddlewareConfig
- type AuthSession
- type AuthSessionStore
- type AuthUser
- type AuthUserStore
- type CORSOptions
- type CSPConfig
- type FrameOptionsConfig
- type HSTSConfig
- type HTTPSRedirectConfig
- type JailBotsConfig
- type SecurityHeadersConfig
- type UserMiddlewareConfig
- type UserMiddlewareUser
- type UserWithRole
- type XSSProtectionConfig
Constants ¶
This section is empty.
Variables ¶
var RequestIDKey = requestIDKey(struct{}{})
RequestIDKey is exported for consumers that need to read the request ID directly from the context. Prefer GetRequestID(ctx) where possible.
Functions ¶
func AuthMiddleware ¶ added in v1.7.0
func AuthMiddleware(config AuthMiddlewareConfig) rtr.MiddlewareInterface
AuthMiddleware creates a middleware that adds the authenticated user and session to the request context.
Business logic:
- Checks if the user session key exists in the incoming request cookie
- Retrieves the session using the session key (with optional memory cache)
- Checks the session is not expired
- Retrieves the user using the user ID from the session (with optional memory cache)
- Stores the user and session object in the request context
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 CORSOptions) rtr.MiddlewareInterface
CORSMiddleware returns a middleware that handles CORS requests. It is a stdlib-only reimplementation of go-chi/cors. By default (via DefaultCORSMiddleware) it allows all origins, common methods, and common headers.
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 and deflate compression based on the client's Accept-Encoding header. This is a stdlib-only reimplementation of chi's middleware.Compress.
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
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.
Behaviour mirrors chi's middleware.Heartbeat:
- Only GET and HEAD methods trigger the heartbeat response.
- Path matching is case-insensitive.
- The response is 200 OK with Content-Type: text/plain and body ".".
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 response status was, and how long it took. This is a stdlib-only reimplementation of chi's middleware.Logger.
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. The profiler is available under /debug/pprof/ and exposes the standard net/http/pprof endpoints (index, cmdline, profile, symbol, trace, and the individual profile handlers). 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
RateLimitByIPMiddleware returns a middleware that limits the number of requests per time window from the same client IP address. The IP is extracted from r.RemoteAddr (the TCP peer address). IPv6 addresses are bucketed by their /64 prefix. This is a stdlib-only reimplementation of go-chi/httprate's LimitByIP.
func RealIPMiddleware ¶ added in v0.10.0
func RealIPMiddleware() rtr.MiddlewareInterface
RealIPMiddleware returns a middleware that sets the client's real IP address in r.RemoteAddr based on proxy headers. It consults True-Client-IP, X-Real-IP, and X-Forwarded-For (in that priority order) and takes the first valid IP address. If none of the headers contain a valid IP, RemoteAddr is left unchanged.
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
RedirectSlashesMiddleware returns a middleware that redirects requests with a trailing slash to the same path without the trailing slash using a 301 (Moved Permanently) redirect.
Behaviour mirrors chi's middleware.RedirectSlashes, with one difference:
- The root path "/" is never redirected.
- Backslashes are normalized to forward slashes to prevent protocol-relative redirects such as "/\evil.com".
- Leading and trailing slashes are trimmed. Internal double slashes in the computed path are also collapsed by http.Redirect when it sets the Location header (e.g. "/api//v1/" → "/api/v1").
- All trailing slashes are collapsed, not just one. chi only stripped a single trailing slash ("/api/v1///" → "/api/v1//"); this implementation trims them all ("/api/v1///" → "/api/v1"). This is an intentional improvement over chi's behaviour.
- The raw query string is preserved on redirect.
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).
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 RemoteAddr (including port) to track request counts. This is a stdlib-only reimplementation of 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, the context is canceled and a 504 Gateway Timeout response is written.
It's required that you select the ctx.Done() channel to check for the signal if the context has reached its deadline and return, otherwise the timeout signal will be just ignored.
Note: the 504 response is only written if the handler has not already written headers. If the handler calls WriteHeader before the deadline, the 504 is silently suppressed by the standard http.ResponseWriter (which only honors the first WriteHeader call). This matches chi's behaviour.
Behaviour mirrors chi's middleware.Timeout.
func UserMiddleware ¶ added in v1.7.0
func UserMiddleware(config UserMiddlewareConfig) rtr.MiddlewareInterface
UserMiddleware creates a middleware that checks if the user is authenticated and active before allowing access to the protected route.
Required config field: GetUser. If missing, the middleware returns HTTP 500 on every request with a descriptive error message.
Business logic:
- user must be authenticated
- user must be active
- user must have completed registration (unless on an exempt path)
- optional role check must pass
func WwwToNakedDomainMiddleware ¶ added in v1.3.0
func WwwToNakedDomainMiddleware() rtr.MiddlewareInterface
WwwToNakedDomainMiddleware redirects requests from the www subdomain to the naked domain.
Types ¶
type AuthLogger ¶ added in v1.7.0
AuthLogger defines the interface for logging
type AuthMiddlewareConfig ¶ added in v1.7.0
type AuthMiddlewareConfig struct {
// SessionStore provides session lookup by key. Required.
SessionStore AuthSessionStore
// UserStore provides user lookup by ID. Required.
UserStore AuthUserStore
// Logger for error logging. Optional.
Logger AuthLogger
// MemoryCache is an optional TTL cache for session/user objects.
MemoryCache *ttlcache.Cache[string, any]
// ContextKeyUser is the context key used to store the authenticated user. Required.
ContextKeyUser any
// ContextKeySession is the context key used to store the session object. Required.
ContextKeySession any
// CookieName is the name of the cookie containing the session key. Required.
CookieName string
}
AuthMiddlewareConfig configures the auth middleware
type AuthSession ¶ added in v1.7.0
AuthSession defines the interface for session operations
type AuthSessionStore ¶ added in v1.7.0
type AuthSessionStore interface {
SessionFindByKey(ctx context.Context, key string) (AuthSession, error)
}
AuthSessionStore defines the interface for session store operations
type AuthUser ¶ added in v1.7.0
type AuthUser interface {
IsActive() bool
IsAdministrator() bool
IsSuperuser() bool
IsRegistrationCompleted() bool
}
AuthUser defines the interface for user operations
type AuthUserStore ¶ added in v1.7.0
AuthUserStore defines the interface for user store operations
type CORSOptions ¶ added in v1.9.0
type CORSOptions struct {
// AllowedOrigins 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. An origin may contain a wildcard (*) to replace
// 0 or more characters (i.e.: http://*.domain.com). Usage of wildcards
// implies a small performance penalty. Only one wildcard can be used per
// origin. Default value is ["*"].
AllowedOrigins []string
// AllowedMethods is a list of methods the client is allowed to use with
// cross-domain requests. Default value is simple methods (HEAD, GET and POST).
AllowedMethods []string
// AllowedHeaders is list of non simple headers the client is allowed to use
// with cross-domain requests. If the special "*" value is present in the
// list, all headers will be allowed. Default value is [] but "Origin" is
// always appended to the list.
AllowedHeaders []string
// ExposedHeaders indicates which headers are safe to expose to the API of a
// CORS API specification.
ExposedHeaders []string
// AllowCredentials indicates whether the request can include user
// credentials like cookies, HTTP authentication or client side SSL
// certificates.
AllowCredentials bool
// MaxAge indicates how long (in seconds) the results of a preflight request
// can be cached.
MaxAge int
// OptionsPassthrough instructs preflight to let other potential next
// handlers to process the OPTIONS method. Turn this on if your application
// handles OPTIONS.
OptionsPassthrough bool
}
CORSOptions configures the behaviour of CORSMiddleware. It mirrors the fields of go-chi/cors.Options so existing callers can migrate by changing only the type name.
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
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 UserMiddlewareConfig ¶ added in v1.7.0
type UserMiddlewareConfig struct {
// GetUser extracts the authenticated user from the request context.
// Returns nil if no user is authenticated. Required.
GetUser func(r *http.Request) UserMiddlewareUser
// RegistrationEnabled indicates whether registration is enabled
RegistrationEnabled bool
// OnNotAuthenticated is called when the user is not authenticated.
// Typically redirects to login with a flash message.
OnNotAuthenticated func(w http.ResponseWriter, r *http.Request)
// OnNotActive is called when the user account is not active.
// Typically redirects to the home page with an error.
OnNotActive func(w http.ResponseWriter, r *http.Request)
// OnRegistrationIncomplete is called when the user hasn't completed registration
// and registration is enabled. Typically redirects to the registration page.
OnRegistrationIncomplete func(w http.ResponseWriter, r *http.Request)
// RegistrationPaths is a list of URL paths that are exempt from the
// registration completion check (e.g. /profile, /register)
RegistrationPaths []string
// RequireRoles is a list of role names. When non-empty, the user must
// have at least one of the specified roles (via UserWithRole.HasRole).
RequireRoles []string
// OnNotAuthorized is called when the user lacks a required role.
// Typically redirects to the home page with an error.
OnNotAuthorized func(w http.ResponseWriter, r *http.Request)
}
UserMiddlewareConfig configures the user middleware
type UserMiddlewareUser ¶ added in v1.7.0
UserMiddlewareUser defines the interface for user middleware user operations
type UserWithRole ¶ added in v1.7.0
type UserWithRole interface {
UserMiddlewareUser
HasRole(role string) bool
}
UserWithRole extends UserMiddlewareUser with role-checking capability. Implementations provide a HasRole method so the middleware can verify arbitrary roles without hardcoding specific role methods.
type XSSProtectionConfig ¶ added in v1.5.0
XSSProtectionConfig configures X-XSS-Protection
Source Files
¶
- auth_middleware.go
- basic_authetication_middleware.go
- clean_path_middleware.go
- compress_middleware.go
- cors_middleware.go
- get_head_middleware.go
- heartbeat_middleware.go
- helpers.go
- https_redirect_middleware.go
- jail_bots_middleware.go
- logger_middleware.go
- naked_domain_to_www_middleware.go
- profiler_middleware.go
- rate_limit_by_ip_middleware.go
- rate_limiter.go
- real_ip_middleware.go
- recovery_middleware.go
- redirect_slashes.go
- request_id_middleware.go
- security_headers_middleware.go
- throttle_middleware.go
- timeout_middleware.go
- user_middleware.go
- www_to_naked_domain_middleware.go