def headerValuePF[T](pf: PartialFunction[HttpHeader, T]): Directive1[T]


Calls the specified partial function with the first request header the function is isDefinedAt and extracts the result of calling the function.

The headerValuePF directive is an alternative syntax version of headerValue.

If the function throws an exception the request is rejected with a MalformedHeaderRejectionMalformedHeaderRejection.

If the function is not defined for any header the request is rejected as “NotFound”.


def extractHostPort: PartialFunction[HttpHeader, Int] = {
  case h: `Host` => h.port

val route =
  headerValuePF(extractHostPort) { port =>
    complete(s"The port was $port")

// tests:
Get("/") ~> Host("example.com", 5043) ~> route ~> check {
  responseAs[String] shouldEqual "The port was 5043"
Get("/") ~> Route.seal(route) ~> check {
  status shouldEqual NotFound
  responseAs[String] shouldEqual "The requested resource could not be found."
final PartialFunction<HttpHeader, Integer> extractHostPort =
  new JavaPartialFunction<HttpHeader, Integer>() {
    public Integer apply(HttpHeader x, boolean isCheck) throws Exception {
      if (x instanceof Host) {
        if (isCheck) {
          return null;
        } else {
          return ((Host) x).port();
      } else {
        throw noMatch();

final Route route = headerValuePF(extractHostPort, port ->
  complete("The port was " + port)

// tests:
testRoute(route).run(HttpRequest.GET("/").addHeader(Host.create("example.com", 5043)))
  .assertEntity("The port was 5043");

  .assertEntity("The requested resource could not be found.");
The source code for this page can be found here.