optionalHeaderValueByType

optionalHeaderValueByType

Description

Optionally extracts the value of the HTTP request header of the given type.

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

注釈

Custom headers will only be matched by this directive if they extend ModeledCustomHeader from the Scala DSL and there is currently no API for the Java DSL (Ticket #20415)

To learn more about defining custom headers, read: Custom Headers.

Example

final Route route = optionalHeaderValueByType(Origin.class, origin -> {
  if (origin.isPresent()) {
    return complete("The first origin was " + origin.get().getOrigins().iterator().next());
  } else {
    return complete("No Origin header found.");
  }
});

// tests:

// extract Some(header) if the type is matching
Host host = Host.create("localhost", 8080);
Origin originHeader = Origin.create(HttpOrigin.create("http", host));
testRoute(route).run(HttpRequest.GET("abc").addHeader(originHeader))
                .assertEntity("The first origin was http://localhost:8080");

// extract None if no header of the given type is present
testRoute(route).run(HttpRequest.GET("abc")).assertEntity("No Origin header found.");

Contents