Skip to content

Commit

Permalink
can use the http.Request.PathValue method to read route variables w…
Browse files Browse the repository at this point in the history
…hen using go1.22 and above
  • Loading branch information
hidu committed Aug 15, 2024
1 parent db9d1d0 commit 5da4f4e
Show file tree
Hide file tree
Showing 5 changed files with 48 additions and 5 deletions.
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
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

0 comments on commit 5da4f4e

Please sign in to comment.