diff --git a/router.go b/router.go index 385c049b..46d3d689 100644 --- a/router.go +++ b/router.go @@ -122,6 +122,11 @@ func ParamsFromContext(ctx context.Context) Params { return p } +// RequestParam retrieves the parameter from the request context. +func RequestParam(r *http.Request, key string) string { + return ParamsFromContext(r.Context()).ByName(key) +} + // MatchedRoutePathParam is the Param name under which the path of the matched // route is stored, if Router.SaveMatchedRoutePath is set. var MatchedRoutePathParam = "$matchedRoutePath" diff --git a/router_test.go b/router_test.go index ae7d2435..167c6f33 100644 --- a/router_test.go +++ b/router_test.go @@ -5,6 +5,7 @@ package httprouter import ( + "context" "errors" "fmt" "net/http" @@ -610,6 +611,16 @@ func TestRouterParamsFromContext(t *testing.T) { } } +func TestRequestParam(t *testing.T) { + params := Params{Param{"name", "gopher"}} + ctx := context.WithValue(context.Background(), ParamsKey, params) + r, _ := http.NewRequestWithContext(ctx, http.MethodGet, "/user/gopher", nil) + + if p := RequestParam(r, "name"); p != "gopher" { + t.Fatalf("Wrong parameter values: want gopher, got %s", p) + } +} + func TestRouterMatchedRoutePath(t *testing.T) { route1 := "/user/:name" routed1 := false