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 Option 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 ModeledCustomHeader and provide a companion extending ModeledCustomHeaderCompanion, otherwise the routing infrastructure does now know where to search for the needed companion and header name.

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

Example

val 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."
}
The source code for this page can be found here.