pathPrefixTest
Description
Checks whether the unmatched path of the RequestContext
RequestContext
has a prefix matched by the given PathMatcher
. Potentially extracts one or more values (depending on the type of the argument) but doesn’t consume its match from the unmatched path.
This directive is very similar to the pathPrefix directive with the one difference that the path prefix it matched (if it matched) is not consumed. The unmatched path of the RequestContext
RequestContext
is therefore left as is even in the case that the directive successfully matched and the request is passed on to its inner route.
For more info on how to create a PathMatcher
see The PathMatcher DSL.
As opposed to its rawPathPrefixTest counterpart pathPrefixTest
automatically adds a leading slash to its PathMatcher
argument, you therefore don’t have to start your matching expression with an explicit slash.
Depending on the type of its PathMatcher
argument the pathPrefixTest
directive extracts zero or more values from the URI. If the match fails the request is rejected with an empty rejection set.
Example
- Scala
-
source
val completeWithUnmatchedPath = extractUnmatchedPath { p => complete(p.toString) } val route = pathPrefixTest("foo" | "bar") { concat( pathPrefix("foo") { completeWithUnmatchedPath }, pathPrefix("bar") { completeWithUnmatchedPath } ) } // tests: Get("/foo/doo") ~> route ~> check { responseAs[String] shouldEqual "/doo" } Get("/bar/yes") ~> route ~> check { responseAs[String] shouldEqual "/yes" }
- Java
-
source
import static akka.http.javadsl.server.Directives.path; import static akka.http.javadsl.server.Directives.pathEnd; import static akka.http.javadsl.server.Directives.pathPrefix; import static akka.http.javadsl.server.Directives.pathPrefixTest; final Route route = concat( pathPrefixTest(segment("foo").orElse("bar"), () -> concat( pathPrefix("foo", () -> completeWithUnmatchedPath.get()), pathPrefix("bar", () -> completeWithUnmatchedPath.get()) ) ) ); // tests: testRoute(route).run(HttpRequest.GET("/foo/doo")).assertEntity("/doo"); testRoute(route).run(HttpRequest.GET("/bar/yes")).assertEntity("/yes");