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


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.


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


val route =
  optionalHeaderValueByType[Origin]() {
    case Some(origin)  complete(s"The first origin was ${origin.originList.head}")
    case None          complete("No Origin header found.")

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

// extract None if no header of the given type is present
Get("abc") ~> route ~> check {
  responseAs[String] === "No Origin header found."