URLParam sometimes returns URL-encoded variables
- Dominant language
- Go
- Stars
- 22.8k
- Forks
- 1.2k
- Avg merge
- 5h 17m
- Merged PRs (30d)
- 10
Description
Hello!
As the title says, when I try to get a URL parameter from a `http.Request` object (calling `chi.URLParam`), it sometimes returns a URL-encoded result, and it only depends on whether `r.URL.RawPath` is set or not.
This is because in function `*Mux.routeHTTP()`, it checks if `r.URL.RawPath` is set and uses it instead of `r.URL.Path`; however, `r.URL.RawPath` is only present sometimes:
https://github.com/go-chi/chi/blob/7f280968675bcc9f310008fc6b8abff0b923734c/mux.go#L420-L431
IMHO, the best course of action will be to use `url.EscapedPath()` to get the `routePath` and then `url.PathUnescape()` to set every value.
Simple program to show the bug:
```go
package main
import (
"fmt"
"net/http"
"github.com/go-chi/chi/v5"
)
func main() {
r := chi.NewRouter()
r.Get("/{key}", func(w http.ResponseWriter, r *http.Request) {
key := chi.URLParam(r, "key")
fmt.Printf("Path=%q RawPath=%q key=%q\n", r.URL.Path, r.URL.RawPath, key)
fmt.Fprintf(w, "Path=%q RawPath=%q key=%q\n", r.URL.Path, r.URL.RawPath, key)
})
http.ListenAndServe(":3333", r)
}
```
Simple execution to see the problem:
```
$ curl "http://localhost:3333/It%20is%20great"
Path="/It is great" RawPath="" key="It is great"
$ curl "http://localhost:3333/It's%20great"
Path="/It's great" RawPath="/It's%20great" key="It's%20great"
```
If it is OK for you, I will open a Pull Request.
Thank you very much,
Juan
Contributor guide
Research direction
Start in mux.go at Mux.routeHTTP, especially the linked path-selection code, and reproduce the differing URLParam results with the curl examples in the issue. Trace how the selected route path becomes URL parameters and verify that encoded values are decoded consistently whether URL.RawPath is set or empty. Done means both examples return the same decoded parameter value.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- go
- Domain
- api, backend
- Issue type
- Bug
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Clearly specified
- Newbie friendliness
- 55/100