Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

read route variables by http.Request.PathValue when using go1.22 and above #768

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
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
2 changes: 1 addition & 1 deletion .github/workflows/security.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ jobs:
scan:
strategy:
matrix:
go: ['1.20','1.21']
go: ['1.20','1.21','1.22']
fail-fast: true
runs-on: ubuntu-latest
steps:
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ jobs:
unit:
strategy:
matrix:
go: ['1.20','1.21']
go: ['1.20','1.21','1.22']
os: [ubuntu-latest, macos-latest, windows-latest]
fail-fast: true
runs-on: ${{ matrix.os }}
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/verify.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ jobs:
lint:
strategy:
matrix:
go: ['1.20','1.21']
go: ['1.20','1.21','1.22']
fail-fast: true
runs-on: ubuntu-latest
steps:
Expand Down
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,14 @@ func ArticlesCategoryHandler(w http.ResponseWriter, r *http.Request) {
}
```

When using Go 1.22 and above, you also can use the `http.Request.PathValue` method to read route variables:
```go
func ArticlesCategoryHandler(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, "Category: %v\n", r.PathValue("category"))
}
```

And this is all you need to know about the basic usage. More advanced options are explained below.

### Matching Routes
Expand Down
5 changes: 5 additions & 0 deletions doc.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,11 @@ this, convert any capturing groups to non-capturing, e.g. change "/{sort:(asc|de
"/{sort:(?:asc|desc)}". This is a change from prior versions which behaved unpredictably
when capturing groups were present.

When using Go 1.22 and above, you also can use the `http.Request.PathValue` method to
read route variables:

r.PathValue("category")

And this is all you need to know about the basic usage. More advanced options
are explained below.

Expand Down
19 changes: 19 additions & 0 deletions mux.go
Original file line number Diff line number Diff line change
Expand Up @@ -494,17 +494,36 @@ func requestWithVars(r *http.Request, vars map[string]string) *http.Request {
if len(vars) == 0 {
return r
}
var ro any = r
if rr, ok := ro.(canSetPathValue); ok {
for k, v := range vars {
rr.SetPathValue(k, v)
}
}
ctx := context.WithValue(r.Context(), varsKey, vars)
return r.WithContext(ctx)
}

// canSetPathValue is an interface introduced in Go 1.22.0.
// The http.Request type added methods PathValue and SetPathValue,
// which are used to handle named path wildcards in URL routes.
type canSetPathValue interface {
SetPathValue(name, value string)
}

// requestWithRouteAndVars adds the matched route and vars to the request ctx.
// It saves extra allocations in cloning the request once and skipping the
//
// population of empty vars, which in turn mux.Vars can handle gracefully.
func requestWithRouteAndVars(r *http.Request, route *Route, vars map[string]string) *http.Request {
ctx := context.WithValue(r.Context(), routeKey, route)
if len(vars) > 0 {
var ro any = r
if rr, ok := ro.(canSetPathValue); ok {
for k, v := range vars {
rr.SetPathValue(k, v)
}
}
ctx = context.WithValue(ctx, varsKey, vars)
}
return r.WithContext(ctx)
Expand Down
19 changes: 15 additions & 4 deletions mux_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2970,17 +2970,28 @@ func TestContextMiddleware(t *testing.T) {

r := NewRouter()
r.Handle("/path/{foo}", withTimeout(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
vars := Vars(r)
if vars["foo"] != "bar" {
t.Fatal("Expected foo var to be set")
}
checkRouteVar(t, r, "foo", "bar")
})))

rec := NewRecorder()
req := newRequest("GET", "/path/bar")
r.ServeHTTP(rec, req)
}

func checkRouteVar(t *testing.T, r *http.Request, name string, want string) {
t.Helper()
vars := Vars(r)
if vars[name] != want {
t.Fatalf("Expected var %s = %q, but got %q", name, want, vars[name])
}
var ro any = r
if rr, ok := ro.(interface{ PathValue(string) string }); ok {
if val := rr.PathValue(name); val != want {
t.Fatalf("Expected r.PathValue(%s) = %q, but got %q", name, want, val)
}
}
}

func TestGetVarNames(t *testing.T) {
r := NewRouter()

Expand Down