host

Filter requests matching conditions against the hostname part of the Host header value in the request.

There are a few variants:

  • reject all requests with a hostname different from the given ones
  • reject all requests for which the hostname does not satisfy the given predicate
  • reject all requests for which the hostname does not satisfy the given regular expression

The regular expression matching works a little bit different: it rejects all requests with a hostname that doesn’t have a prefix matching the given regular expression and also extracts a String to its inner route following this rules:

  • For all matching requests the prefix string matching the regex is extracted and passed to the inner route.
  • If the regex contains a capturing group only the string matched by this group is extracted.
  • If the regex contains more than one capturing group an IllegalArgumentException is thrown.

Example

Matching a list of hosts:

final Route matchListOfHosts = host(
    Arrays.asList("api.company.com", "rest.company.com"),
    () -> complete(StatusCodes.OK));

testRoute(matchListOfHosts).run(HttpRequest.GET("/").addHeader(Host.create("api.company.com")))
    .assertStatusCode(StatusCodes.OK);

Making sure the host satisfies the given predicate

final Route shortOnly = host(hostname -> hostname.length() < 10,
    () -> complete(StatusCodes.OK));

testRoute(shortOnly).run(HttpRequest.GET("/").addHeader(Host.create("short.com")))
    .assertStatusCode(StatusCodes.OK);

testRoute(shortOnly).run(HttpRequest.GET("/").addHeader(Host.create("verylonghostname.com")))
    .assertStatusCode(StatusCodes.NOT_FOUND);

Using a regular expressions:


final Route hostPrefixRoute = host(Pattern.compile("api|rest"), prefix -> complete("Extracted prefix: " + prefix)); final Route hostPartRoute = host(Pattern.compile("public.(my|your)company.com"), captured -> complete("You came through " + captured + " company")); final Route route = route(hostPrefixRoute, hostPartRoute); testRoute(route).run(HttpRequest.GET("/").addHeader(Host.create("api.company.com"))) .assertStatusCode(StatusCodes.OK).assertEntity("Extracted prefix: api"); testRoute(route).run(HttpRequest.GET("/").addHeader(Host.create("public.mycompany.com"))) .assertStatusCode(StatusCodes.OK) .assertEntity("You came through my company");

Beware that in the case of introducing multiple capturing groups in the regex such as in the case bellow, the directive will fail at runtime, at the moment the route tree is evaluated for the first time. This might cause your http handler actor to enter in a fail/restart loop depending on your supervision strategy.

// this will throw IllegalArgumentException
final Route hostRegex = host(Pattern.compile("server-([0-9]).company.(com|net|org)"), s ->
    // will not reach here
    complete(s)
);
The source code for this page can be found here.