headerValueByName

Description

Extracts the value of the HTTP request header with the given name.

If no header with a matching name is found the request is rejected with a MissingHeaderRejection.

If the header is expected to be missing in some cases or to customize handling when the header is missing use the optionalHeaderValueByName directive instead.

Example

final Route route = headerValueByName("X-User-Id", userId ->
  complete("The user is " + userId)
);

// 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("/"))
  .assertStatusCode(StatusCodes.BAD_REQUEST)
  .assertEntity("Request is missing required HTTP header 'X-User-Id'");
The source code for this page can be found here.