optionalHeaderValueByName
Signature
Description
Optionally extracts the value of the HTTP request header with the given name.
The optionalHeaderValueByName
directive is similar to the headerValueByName directive but always extracts
an Option
value instead of rejecting the request if no matching header could be found.
Example
val route =
optionalHeaderValueByName("X-User-Id") {
case Some(userId) => complete(s"The user is $userId")
case None => complete(s"No user was provided")
} ~ // can also be written as:
optionalHeaderValueByName("port") { port =>
complete {
port match {
case Some(p) => s"The user is $p"
case _ => "No user was provided"
}
}
}
// tests:
Get("/") ~> RawHeader("X-User-Id", "Joe42") ~> route ~> check {
responseAs[String] shouldEqual "The user is Joe42"
}
Get("/") ~> Route.seal(route) ~> check {
responseAs[String] shouldEqual "No user was provided"
}
Contents