headerValue

headerValue

Signature

Description

Traverses the list of request headers with the specified function and extracts the first value the function returns as Some(value).

The headerValue directive is a mixture of map and find on the list of request headers. The specified function is called once for each header until the function returns Some(value). This value is extracted and presented to the inner route. If the function throws an exception the request is rejected with a MalformedHeaderRejection. If the function returns None for every header the request is rejected as "NotFound".

This directive is the basis for building other request header related directives.

See also headerValuePF for a nicer syntactic alternative.

Example

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

val route =
  headerValue(extractHostPort) { port =>
    complete(s"The port was $port")
  }

// tests:
Get("/") ~> Host("example.com", 5043) ~> route ~> check {
  responseAs[String] shouldEqual "The port was 5043"
}
Get("/") ~> Route.seal(route) ~> check {
  status shouldEqual NotFound
  responseAs[String] shouldEqual "The requested resource could not be found."
}

Contents