TrailingSlashMiddleware redirects requests with trailing slashes to their canonical form
(next http.Handler)
| 69 | |
| 70 | // TrailingSlashMiddleware redirects requests with trailing slashes to their canonical form |
| 71 | func TrailingSlashMiddleware(next http.Handler) http.Handler { |
| 72 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 73 | // Only redirect if the path is not "/" and ends with a "/" |
| 74 | if r.URL.Path != "/" && strings.HasSuffix(r.URL.Path, "/") { |
| 75 | // path.Clean both removes the trailing slash and collapses any |
| 76 | // leading "//" to "/", which prevents an open-redirect via a |
| 77 | // protocol-relative path like "//evil.com/" (GHSA-v8vw-gw5j-w7m6). |
| 78 | newURL := *r.URL |
| 79 | newURL.Path = path.Clean(r.URL.Path) |
| 80 | |
| 81 | // Use 308 Permanent Redirect to preserve the request method |
| 82 | http.Redirect(w, r, newURL.String(), http.StatusPermanentRedirect) |
| 83 | return |
| 84 | } |
| 85 | |
| 86 | next.ServeHTTP(w, r) |
| 87 | }) |
| 88 | } |
| 89 | |
| 90 | // Server represents the HTTP server |
| 91 | type Server struct { |
searching dependent graphs…