optionalHeaderValue

optionalHeaderValue

Description

Traverses the list of request headers with the specified function and extracts the first value the function returns as Optional[value].

The optionalHeaderValue directive is similar to the headerValue directive but always extracts an Option value instead of rejecting the request if no matching header could be found.

Example

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

final Route route = optionalHeaderValue(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