headerValueByType

Traverses the list of request headers and extracts the first header of the given type.

Signature

def headerValueByType[T <: HttpHeader: ClassTag](): Directive1[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

The headerValueByType directive finds a header of the given type in the list of request header. If no header of the given type is found the request is rejected with a MissingHeaderRejection. If the header is expected to be missing in some cases or to customize handling when the header is missing use the optionalHeaderValueByType directive instead.

Example

val route =
  headerValueByType[Origin]() { origin 
    complete(s"The first origin was ${origin.originList.head}")
  }

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

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

// reject a request if no header of the given type is present
Get("abc") ~> route ~> check {
  rejection must beLike { case MissingHeaderRejection("Origin")  ok }
}