optionalHeaderValueByName

Description

Optionally extracts the value of the HTTP request header with the given name.

The optionalHeaderValueByName directive is similar to the headerValueByName directive but always extracts an Optional value instead of rejecting the request if no matching header could be found.

Example

final Route route = optionalHeaderValueByName("X-User-Id", userId -> {
  if (userId.isPresent()) {
    return complete("The user is " + userId.get());
  } else {
    return complete("No user was provided");
  }
});

// tests:
final RawHeader header = RawHeader.create("X-User-Id", "Joe42");
testRoute(route).run(HttpRequest.GET("/").addHeader(header))
  .assertEntity("The user is Joe42");

testRoute(route).run(HttpRequest.GET("/")).assertEntity("No user was provided");
The source code for this page can be found here.