diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..8899521 --- /dev/null +++ b/go.mod @@ -0,0 +1,5 @@ +module github.com/madalynerlge2/chi + +go 1.25.12 + +require github.com/go-chi/chi/v5 v5.3.1 // indirect diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..bdb0eaa --- /dev/null +++ b/go.sum @@ -0,0 +1,2 @@ +github.com/go-chi/chi/v5 v5.3.1 h1:3j4HZLGZQ3JpMCrPJF/Jl3mYJfWLKBfNJ6quurUGCf8= +github.com/go-chi/chi/v5 v5.3.1/go.mod h1:R+tYY2hNuVUUjxoPtqUdgBqevM9s9njzkTLutVsOCto= diff --git a/rewrite.go b/rewrite.go new file mode 100644 index 0000000..7951715 --- /dev/null +++ b/rewrite.go @@ -0,0 +1,16 @@ +package chi + +import ( + "net/http" + + "github.com/go-chi/chi/v5" +) + +// RewritePath safely updates both the Request URL Path and the chi routing context. +// This prevents URL parameter loss when middleware forcibly overwrites Request.URL.Path. +func RewritePath(r *http.Request, newPath string) { + r.URL.Path = newPath + if rctx := chi.RouteContext(r.Context()); rctx != nil { + rctx.RoutePath = newPath + } +} diff --git a/rewrite_test.go b/rewrite_test.go new file mode 100644 index 0000000..d40abac --- /dev/null +++ b/rewrite_test.go @@ -0,0 +1,42 @@ +package chi + +import ( + "net/http" + "net/http/httptest" + "testing" + + "github.com/go-chi/chi/v5" +) + +func TestRewritePath(t *testing.T) { + r := chi.NewRouter() + + // Middleware that rewrites the path using the new helper + r.Use(func(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + if req.URL.Path == "/legacy/123" { + RewritePath(req, "/users/123") + } + next.ServeHTTP(w, req) + }) + }) + + r.Get("/users/{id}", func(w http.ResponseWriter, req *http.Request) { + id := chi.URLParam(req, "id") + if id != "123" { + t.Errorf("expected URL param 'id' to be '123', got '%s'", id) + } + w.Write([]byte("ok")) + }) + + ts := httptest.NewServer(r) + defer ts.Close() + + res, err := http.Get(ts.URL + "/legacy/123") + if err != nil { + t.Fatal(err) + } + if res.StatusCode != http.StatusOK { + t.Errorf("expected status 200, got %d", res.StatusCode) + } +}