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

Add support for r.PathValue when built for Go 1.22. #6

Merged
merged 1 commit into from
Oct 5, 2024
Merged
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
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
}
Loading