optionalHeaderValuePF
Description
Calls the specified partial function with the first request header the function is isDefinedAt
and extracts the
result of calling the function.
The optionalHeaderValuePF
directive is similar to the headerValuePF directive but always extracts an Optional
value instead of rejecting the request if no matching header could be found.
Example
final PartialFunction<HttpHeader, Integer> extractHostPort =
new JavaPartialFunction<HttpHeader, Integer>() {
@Override
public Integer apply(HttpHeader x, boolean isCheck) throws Exception {
if (x instanceof Host) {
if (isCheck) {
return null;
} else {
return ((Host) x).port();
}
} else {
throw noMatch();
}
}
};
final Route route = optionalHeaderValuePF(extractHostPort, port -> {
if (port.isPresent()) {
return complete("The port was " + port.get());
} else {
return complete("The port was not provided explicitly");
}
});
// tests:
testRoute(route).run(HttpRequest.GET("/").addHeader(Host.create("example.com", 5043)))
.assertEntity("The port was 5043");
testRoute(route).run(HttpRequest.GET("/"))
.assertEntity("The port was not provided explicitly");
Contents