headerValue

Signature

def headerValue[T](f: HttpHeader => Option[T]): Directive1[T]

Description

Traverses the list of request headers with the specified function and extracts the first value the function returns as Some(value)a non empty Optional<T>.

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)a non empty Optional<T>. This value is extracted and presented to the inner route. If the function throws an exception the request is rejected with a MalformedHeaderRejectionMalformedHeaderRejection. If the function returns NoneOptional.empty() 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

Scala
sourcedef 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."
}
Java
sourceimport static akka.http.javadsl.server.Directives.complete;
import static akka.http.javadsl.server.Directives.headerValue;

final Function<HttpHeader, Optional<Host>> extractHostPort = header -> {
  if (header instanceof Host) {
    return Optional.of((Host) header);
  } else {
    return Optional.empty();
  }
};

final Route route = headerValue(extractHostPort, host ->
  complete("The port was " + host.port())
);

// tests:
testRoute(route).run(HttpRequest.GET("/").addHeader(Host.create("example.com", 5043)))
  .assertEntity("The port was 5043");

testRoute(route).run(HttpRequest.GET("/"))
  .assertStatusCode(StatusCodes.NOT_FOUND)
  .assertEntity("The requested resource could not be found.");

Get headerValue or return a default value

Using provide and composing directives one can build a pattern where a headerValue is extracted if available or a default is returned.

Scala
sourceval exampleHeaderValue = "exampleHeaderValue".toLowerCase
def extractExampleHeader: HttpHeader => Option[String] = {
  case HttpHeader(`exampleHeaderValue`, value) => Some(value)
  case _                                       => None
}

val route =
  (headerValue(extractExampleHeader) | provide("newValue")) { value =>
    complete(s"headerValue $value")
  }

// tests:
Get("/") ~> RawHeader("exampleHeaderValue", "theHeaderValue") ~> route ~> check {
  responseAs[String] shouldEqual "headerValue theHeaderValue"
}

Get("/") ~> route ~> check {
  responseAs[String] shouldEqual "headerValue newValue"
}
Java
sourceimport akka.http.javadsl.server.Directives;

import static akka.http.javadsl.server.Directives.complete;
import static akka.http.javadsl.server.Directives.anyOf;
final Function<HttpHeader, Optional<String>> extractExampleHeader = header -> {
  if (header.is("x-example-header")) {
    return Optional.of(header.value());
  } else {
    return Optional.empty();
  }
};

final Route route = anyOf(
  bindParameter(Directives::headerValue, extractExampleHeader),
  bindParameter(Directives::provide, "newValue"),
  (String value) -> complete("header is " + value));

// tests:
final RawHeader exampleHeader = RawHeader.create("X-Example-Header", "theHeaderValue");
testRoute(route).run(HttpRequest.GET("/").addHeader(exampleHeader))
  .assertEntity("header is theHeaderValue");

testRoute(route).run(HttpRequest.GET("/"))
  .assertEntity("header is newValue");
Found an error in this documentation? The source code for this page can be found here. Please feel free to edit and contribute a pull request.