optionalHeaderValueByType

Signature

def optionalHeaderValueByType[T <: HttpHeader: ClassTag](): Directive1[Option[T]]

The signature shown is simplified, the real signature uses magnets. [1]

[1] See The Magnet Pattern for an explanation of magnet-based overloading.

Description

Optionally extracts the value of the HTTP request header of the given type.

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

Note

Custom headers will only be matched by this directive if they extend ModeledCustomHeaderModeledCustomHeader and provide a companion extending ModeledCustomHeaderCompanion, otherwise the routing infrastructure does now know where to search for the needed companion and header name. from the Scala DSL and there is currently no API for the Java DSL (Issue 219)

To learn more about defining custom headers, read: Custom Headers.

Example

Scala
sourceval route =
  optionalHeaderValueByType(Origin) {
    case Some(origin) => complete(s"The first origin was ${origin.origins.head}")
    case None         => complete("No Origin header found.")
  }

val originHeader = Origin(HttpOrigin("http://localhost:8080"))

// tests:
// extract Some(header) if the type is matching
Get("abc") ~> originHeader ~> route ~> check {
  responseAs[String] shouldEqual "The first origin was http://localhost:8080"
}

// extract None if no header of the given type is present
Get("abc") ~> route ~> check {
  responseAs[String] shouldEqual "No Origin header found."
}
Java
sourceimport static org.apache.pekko.http.javadsl.server.Directives.complete;
import static org.apache.pekko.http.javadsl.server.Directives.optionalHeaderValueByType;

final Route route =
    optionalHeaderValueByType(
        Origin.class,
        origin -> {
          if (origin.isPresent()) {
            return complete(
                "The first origin was " + origin.get().getOrigins().iterator().next());
          } else {
            return complete("No Origin header found.");
          }
        });

// tests:

// extract Some(header) if the type is matching
Host host = Host.create("localhost", 8080);
Origin originHeader = Origin.create(HttpOrigin.create("http", host));
testRoute(route)
    .run(HttpRequest.GET("abc").addHeader(originHeader))
    .assertEntity("The first origin was http://localhost:8080");

// extract None if no header of the given type is present
testRoute(route).run(HttpRequest.GET("abc")).assertEntity("No Origin header found.");