optionalHeaderValuePF

Signature

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

Description

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

The optionalHeaderValuePF directive is similar to the headerValuePF directive but always extracts an OptionOptional value instead of rejecting the request if no matching header could be found.

Example

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

val route =
  optionalHeaderValuePF(extractHostPort) {
    case Some(port) => complete(s"The port was $port")
    case None       => complete(s"The port was not provided explicitly")
  } ~ // can also be written as:
    optionalHeaderValuePF(extractHostPort) { port =>
      complete {
        port match {
          case Some(p) => s"The port was $p"
          case _       => "The port was not provided explicitly"
        }
      }
    }

// tests:
Get("/") ~> Host("example.com", 5043) ~> route ~> check {
  responseAs[String] shouldEqual "The port was 5043"
}
Get("/") ~> Route.seal(route) ~> check {
  responseAs[String] shouldEqual "The port was not provided explicitly"
}
Java
sourceimport static akka.http.javadsl.server.Directives.complete;
import static akka.http.javadsl.server.Directives.optionalHeaderValuePF;

final PartialFunction<HttpHeader, Integer> extractHostPort =
  new JavaPartialFunction<HttpHeader, Integer>() {
    @Override
    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 = optionalHeaderValuePF(extractHostPort, port -> {
  if (port.isPresent()) {
    return complete("The port was " + port.get());
  } else {
    return complete("The port was not provided explicitly");
  }
});

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

testRoute(route).run(HttpRequest.GET("/"))
  .assertEntity("The port was not provided explicitly");
Found an error in this documentation? The source code for this page can be found here. Please feel free to edit and contribute a pull request.