Overview
Theslash middleware handles trailing slashes in URLs by adding or removing them with redirects. Use it for URL consistency and SEO.
Installation
Quick Start
Functions
Examples
Add Trailing Slash
Remove Trailing Slash
Temporary Redirect
Behavior
- Root path
/is never modified - Query strings are preserved
- Uses 301 (Permanent) by default
Technical Details
The slash middleware implements trailing slash normalization through HTTP redirects. It provides four main functions that return middleware handlers:Implementation
- Add(): Wraps
AddCode()with HTTP 301 (Moved Permanently) status - AddCode(code int): Returns middleware that checks if path lacks trailing slash and redirects to add it
- Remove(): Wraps
RemoveCode()with HTTP 301 (Moved Permanently) status - RemoveCode(code int): Returns middleware that checks if path has trailing slash and redirects to remove it
Internal Logic
- Path Extraction: Reads the request URL path from
c.Request().URL.Path - Root Protection: Always skips the root path
/to prevent infinite redirects - Slash Detection: Uses
strings.HasSuffix(path, "/")to check for trailing slash - Target Construction: Builds redirect URL by adding/removing trailing slash
- Query Preservation: Appends
?+c.Request().URL.RawQueryif query string exists - Redirect Execution: Calls
c.Redirect(code, target)with specified status code - Pass-through: Calls
next(c)if no redirect needed
Performance Characteristics
- Zero allocations for paths that donβt need redirection
- Single string concatenation for building redirect target
- Early exit for root path and paths already in correct format
- No regular expressions - uses simple string operations
Best Practices
- Choose one style and be consistent
- Use 301 for permanent SEO benefit
- Apply early in middleware chain