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

  1. final Route route = optionalHeaderValueByType(Origin.class, origin -> {
  2. if (origin.isPresent()) {
  3. return complete("The first origin was " + origin.get().getOrigins().iterator().next());
  4. } else {
  5. return complete("No Origin header found.");
  6. }
  7. });
  8.  
  9. // tests:
  10.  
  11. // extract Some(header) if the type is matching
  12. Host host = Host.create("localhost", 8080);
  13. Origin originHeader = Origin.create(HttpOrigin.create("http", host));
  14. testRoute(route).run(HttpRequest.GET("abc").addHeader(originHeader))
  15. .assertEntity("The first origin was http://localhost:8080");
  16.  
  17. // extract None if no header of the given type is present
  18. testRoute(route).run(HttpRequest.GET("abc")).assertEntity("No Origin header found.");