Skip to content

Commit

Permalink
Add support for r.PathValue when built for Go 1.22.
Browse files Browse the repository at this point in the history
Go 1.22 introduced pattern matching into its ServeMux, and as a result
the net/http.Request type got a PathValue method, returning the value
that matched the given key in the pattern.

We can, and should, populate the data behind that mathod when using
trout's pattern matching, so handlers can standardize on that built-in
function.
  • Loading branch information
paddycarver committed Oct 5, 2024
1 parent 844e004 commit 80a59d6
Show file tree
Hide file tree
Showing 4 changed files with 51 additions and 0 deletions.
3 changes: 3 additions & 0 deletions route.go
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,9 @@ func (router Router) getHandler(r *http.Request) http.Handler {
r.Header.Set("Trout-Pattern", route.pattern)
for key, vals := range route.params {
r.Header[http.CanonicalHeaderKey("Trout-Param-"+key)] = vals
for _, val := range vals {
setBuiltinRequestPathVar(r, key, val)
}
}

// if no handler is set, it could be because there's no handler for
Expand Down
8 changes: 8 additions & 0 deletions route_below_go1_22.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
//go:build !go1.22

package trout

import "net/http"

func setBuiltinRequestPathVar(_ *http.Request, _, _ string) {
}
9 changes: 9 additions & 0 deletions route_go1_22.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
//go:build go1.22

package trout

import "net/http"

func setBuiltinRequestPathVar(r *http.Request, name, value string) {
r.SetPathValue(name, value)
}
31 changes: 31 additions & 0 deletions route_go1_22_examples_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
//go:build go1.22

package trout_test

import (
"net/http"

"darlinggo.co/trout/v2"
)

func ExampleRouter_Endpoint_pathValues() {
postsHandler := http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
// we populate the PathValue request property introduced
// in Go 1.22 when you build with Go 1.22.
id := r.PathValue("id")
_, err := w.Write([]byte(id))
if err != nil {
panic(err)
}
})

var router trout.Router
router.Endpoint("/posts/{id}").Handler(postsHandler)

req, _ := http.NewRequest("GET", "http://example.com/posts/foo", nil)
router.ServeHTTP(exampleResponseWriter{}, req)

// Output:
// foo
}

0 comments on commit 80a59d6

Please sign in to comment.