Skip to content

Commit

Permalink
Unescape HTTP path parameters (#3364)
Browse files Browse the repository at this point in the history
* Add cases to http.TestVars()

* Unescape HTTP path parameters
  • Loading branch information
tchssk authored Sep 26, 2023
1 parent 93f9342 commit 09e20be
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 2 deletions.
13 changes: 11 additions & 2 deletions http/mux.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"fmt"
"net/http"
"net/url"
"regexp"

chi "github.com/go-chi/chi/v5"
Expand Down Expand Up @@ -113,14 +114,22 @@ func (m *mux) Vars(r *http.Request) map[string]string {
for i, k := range params.Keys {
if k == "*" {
wildcard := m.wildcards[r.Method+"::"+rctx.RoutePattern()]
vars[wildcard] = params.Values[i]
vars[wildcard] = unescape(params.Values[i])
continue
}
vars[k] = params.Values[i]
vars[k] = unescape(params.Values[i])
}
return vars
}

func unescape(s string) string {
u, err := url.PathUnescape(s)
if err != nil {
return s
}
return u
}

// Use appends a middleware to the list of middlewares to be applied
// downstream the Muxer.
func (m *mux) Use(f func(http.Handler) http.Handler) {
Expand Down
17 changes: 17 additions & 0 deletions http/mux_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,23 @@ func TestVars(t *testing.T) {
"post_id": "456/789",
},
},
{
Name: "escaped",
Pattern: "/users/{id}",
URL: "/users/%40123",
Expected: map[string]string{
"id": "@123",
},
},
{
Name: "escaped wildcard",
Pattern: "/users/{id}/posts/{*post_id}",
URL: "/users/%40123/posts/456/789%24",
Expected: map[string]string{
"id": "@123",
"post_id": "456/789$",
},
},
{
Name: "no var",
Pattern: "/users",
Expand Down

0 comments on commit 09e20be

Please sign in to comment.