Documentation
¶
Index ¶
- Constants
- func AuthMiddleware(config AuthMiddlewareConfig) rtr.MiddlewareInterface
- func BasicAuthenticationMiddleware(username string, password string) rtr.MiddlewareInterface
- func CORSMiddleware(opts cors.Options) 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 CSPConfig
- type FrameOptionsConfig
- type HSTSConfig
- type HTTPSRedirectConfig
- type JailBotsConfig
- type SecurityHeadersConfig
- type UserMiddlewareConfig
- type UserMiddlewareUser
- type UserWithRole
- type XSSProtectionConfig
Constants ¶
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 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 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
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 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 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
- 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