strip.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package middleware
  2. import (
  3. "fmt"
  4. "net/http"
  5. "strings"
  6. "github.com/go-chi/chi/v5"
  7. )
  8. // StripSlashes is a middleware that will match request paths with a trailing
  9. // slash, strip it from the path and continue routing through the mux, if a route
  10. // matches, then it will serve the handler.
  11. func StripSlashes(next http.Handler) http.Handler {
  12. fn := func(w http.ResponseWriter, r *http.Request) {
  13. var path string
  14. rctx := chi.RouteContext(r.Context())
  15. if rctx != nil && rctx.RoutePath != "" {
  16. path = rctx.RoutePath
  17. } else {
  18. path = r.URL.Path
  19. }
  20. if len(path) > 1 && path[len(path)-1] == '/' {
  21. newPath := path[:len(path)-1]
  22. if rctx == nil {
  23. r.URL.Path = newPath
  24. } else {
  25. rctx.RoutePath = newPath
  26. }
  27. }
  28. next.ServeHTTP(w, r)
  29. }
  30. return http.HandlerFunc(fn)
  31. }
  32. // RedirectSlashes is a middleware that will match request paths with a trailing
  33. // slash and redirect to the same path, less the trailing slash.
  34. //
  35. // NOTE: RedirectSlashes middleware is *incompatible* with http.FileServer,
  36. // see https://github.com/go-chi/chi/issues/343
  37. func RedirectSlashes(next http.Handler) http.Handler {
  38. fn := func(w http.ResponseWriter, r *http.Request) {
  39. var path string
  40. rctx := chi.RouteContext(r.Context())
  41. if rctx != nil && rctx.RoutePath != "" {
  42. path = rctx.RoutePath
  43. } else {
  44. path = r.URL.Path
  45. }
  46. if len(path) > 1 && path[len(path)-1] == '/' {
  47. // Normalize backslashes to forward slashes to prevent "/\evil.com" style redirects
  48. // that some clients may interpret as protocol-relative.
  49. path = strings.ReplaceAll(path, `\`, `/`)
  50. // Collapse leading/trailing slashes and force a single leading slash.
  51. path := "/" + strings.Trim(path, "/")
  52. if r.URL.RawQuery != "" {
  53. path = fmt.Sprintf("%s?%s", path, r.URL.RawQuery)
  54. }
  55. http.Redirect(w, r, path, 301)
  56. return
  57. }
  58. next.ServeHTTP(w, r)
  59. }
  60. return http.HandlerFunc(fn)
  61. }
  62. // StripPrefix is a middleware that will strip the provided prefix from the
  63. // request path before handing the request over to the next handler.
  64. func StripPrefix(prefix string) func(http.Handler) http.Handler {
  65. return func(next http.Handler) http.Handler {
  66. return http.StripPrefix(prefix, next)
  67. }
  68. }