StripSlashes is a middleware that will match request paths with a trailing slash, strip it from the path and continue routing through the mux, if a route matches, then it will serve the handler.
(next http.Handler)
| 12 | // slash, strip it from the path and continue routing through the mux, if a route |
| 13 | // matches, then it will serve the handler. |
| 14 | func StripSlashes(next http.Handler) http.Handler { |
| 15 | fn := func(w http.ResponseWriter, r *http.Request) { |
| 16 | var path string |
| 17 | rctx := chi.RouteContext(r.Context()) |
| 18 | if rctx != nil && rctx.RoutePath != "" { |
| 19 | path = rctx.RoutePath |
| 20 | } else { |
| 21 | path = r.URL.Path |
| 22 | } |
| 23 | if len(path) > 1 && path[len(path)-1] == '/' { |
| 24 | newPath := path[:len(path)-1] |
| 25 | if rctx == nil { |
| 26 | r.URL.Path = newPath |
| 27 | } else { |
| 28 | rctx.RoutePath = newPath |
| 29 | } |
| 30 | } |
| 31 | next.ServeHTTP(w, r) |
| 32 | } |
| 33 | return http.HandlerFunc(fn) |
| 34 | } |
| 35 | |
| 36 | // RedirectSlashes is a middleware that will match request paths with a trailing |
| 37 | // slash and redirect to the same path, less the trailing slash. |