clean_path.go 658 B

12345678910111213141516171819202122232425262728
  1. package middleware
  2. import (
  3. "net/http"
  4. "path"
  5. "github.com/go-chi/chi/v5"
  6. )
  7. // CleanPath middleware will clean out double slash mistakes from a user's request path.
  8. // For example, if a user requests /users//1 or //users////1 will both be treated as: /users/1
  9. func CleanPath(next http.Handler) http.Handler {
  10. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  11. rctx := chi.RouteContext(r.Context())
  12. routePath := rctx.RoutePath
  13. if routePath == "" {
  14. if r.URL.RawPath != "" {
  15. routePath = r.URL.RawPath
  16. } else {
  17. routePath = r.URL.Path
  18. }
  19. rctx.RoutePath = path.Clean(routePath)
  20. }
  21. next.ServeHTTP(w, r)
  22. })
  23. }