host

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

Signature

def host(hostNames: String*): Directive0 
def host(predicate: String  Boolean): Directive0 
def host(regex: Regex): Directive1[String] 

Description

The def host(hostNames: String*) overload rejects all requests with a hostname different from the given ones.

The def host(predicate: String Boolean) overload rejects all requests for which the hostname does not satisfy the given predicate.

The def host(regex: Regex) overload 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:

val route =
  host("api.company.com", "rest.company.com") {
    complete("Ok")
  }

Get() ~> Host("rest.company.com") ~> route ~> check {
  status === OK
  responseAs[String] === "Ok"
}

Get() ~> Host("notallowed.company.com") ~> route ~> check {
  handled must beFalse
}

Making sure the host satisfies the given predicate

val shortOnly: String => Boolean = (hostname) => hostname.length < 10

val route =
  host(shortOnly) {
    complete("Ok")
  }

Get() ~> Host("short.com") ~> route ~> check {
  status === OK
  responseAs[String] === "Ok"
}

Get() ~> Host("verylonghostname.com") ~> route ~> check {
  handled must beFalse
}

Using a regular expressions:

val route =
  host("api|rest".r) { prefix =>
    complete(s"Extracted prefix: $prefix")
  } ~
  host("public.(my|your)company.com".r) { captured =>
    complete(s"You came through $captured company")
  }

Get() ~> Host("api.company.com") ~> route ~> check {
  status === OK
  responseAs[String] === "Extracted prefix: api"
}

Get() ~> Host("public.mycompany.com") ~> route ~> check {
  status === OK
  responseAs[String] === "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.

{
  host("server-([0-9]).company.(com|net|org)".r) { target =>
    complete("Will never complete :'(")
  }
} must throwAn[IllegalArgumentException]