optionalHeaderValueByName

Signature

def optionalHeaderValueByName(headerName: Symbol): Directive1[Option[String]]
def optionalHeaderValueByName(headerName: String): Directive1[Option[String]]

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 OptionOptional value instead of rejecting the request if no matching header could be found.

Example

Scala
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"
}
Java
final Route route = optionalHeaderValueByName("X-User-Id", userId -> {
  if (userId.isPresent()) {
    return complete("The user is " + userId.get());
  } else {
    return complete("No user was provided");
  }
});

// tests:
final RawHeader header = RawHeader.create("X-User-Id", "Joe42");
testRoute(route).run(HttpRequest.GET("/").addHeader(header))
  .assertEntity("The user is Joe42");

testRoute(route).run(HttpRequest.GET("/")).assertEntity("No user was provided");
The source code for this page can be found here.