optionalAttribute
Description
Optionally extracts the value of the request attribute with the given key.
The optionalAttribute
directive is similar to the attribute directive but always extracts an Option
value instead of rejecting the request if no matching attribute could be found.
Example
- Scala
-
source
val userId = AttributeKey[String]("user-id") val route = optionalAttribute(userId) { case Some(userId) => complete(s"The user is $userId") case None => complete(s"No user was provided") } ~ // can also be written as: optionalAttribute(userId) { userId => complete { userId match { case Some(u) => s"The user is $u" case _ => "No user was provided" } } } // tests: Get("/") ~> addAttribute(userId, "Joe42") ~> route ~> check { responseAs[String] shouldEqual "The user is Joe42" } Get("/") ~> Route.seal(route) ~> check { responseAs[String] shouldEqual "No user was provided" }
- Java