headerValue
Description
Traverses the list of request headers with the specified function and extracts the first value the function returns as
Optional[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 Optional(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 Optional.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
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.");
Contents