optionalHeaderValue

Signature

def optionalHeaderValue[T](f: HttpHeader => Option[T]): Directive1[Option[T]]

Description

Traverses the list of request headers with the specified function and extracts the first value the function returns as Some(value)a non empty Optional<T>.

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

Example

Scala
sourcedef extractHostPort: HttpHeader => Option[Int] = {
  case h: `Host` => Some(h.port)
  case x         => None
}

val route =
  optionalHeaderValue(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:
    optionalHeaderValue(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.optionalHeaderValue;

final Function<HttpHeader, Optional<Integer>> extractHostPort = header -> {
  if (header instanceof Host) {
    return Optional.of(((Host) header).port());
  } else {
    return Optional.empty();
  }
};

final Route route = optionalHeaderValue(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.