Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
module github.com/madalynerlge2/chi

go 1.25.12

require github.com/go-chi/chi/v5 v5.3.1 // indirect
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -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=
16 changes: 16 additions & 0 deletions rewrite.go
Original file line number Diff line number Diff line change
@@ -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
}
}
42 changes: 42 additions & 0 deletions rewrite_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}