selectPreferredLanguage

Signature

def selectPreferredLanguage(first: Language, more: Language*): Directive1[Language] 

Description

Inspects the request’s Accept-Language header and determines, which of a given set of language alternatives is preferred by the client according to content negotiation rules defined by RFC 7231 in section 5.3.5.

If there are several best language alternatives that the client has equal preference for (even if this preference is zero!) the order of the arguments is used as a tie breaker (first one wins).

Example

Scala
sourceval request = Get() ~> `Accept-Language`(
  Language("en-US"),
  Language("en").withQValue(0.7f),
  LanguageRange.`*`.withQValue(0.1f),
  Language("de").withQValue(0.5f))

request ~> {
  selectPreferredLanguage("en", "en-US") { lang =>
    complete(lang.toString)
  }
} ~> check { responseAs[String] shouldEqual "en-US" }

request ~> {
  selectPreferredLanguage("de-DE", "hu") { lang =>
    complete(lang.toString)
  }
} ~> check { responseAs[String] shouldEqual "de-DE" }
Java
sourceimport static org.apache.pekko.http.javadsl.server.Directives.complete;
import static org.apache.pekko.http.javadsl.server.Directives.selectPreferredLanguage;

final Route enRoute =
    selectPreferredLanguage(
        Arrays.asList(Language.create("en"), Language.create("en-US")),
        lang -> complete(lang.toString()));
final Route deHuRoute =
    selectPreferredLanguage(
        Arrays.asList(Language.create("de-DE"), Language.create("hu")),
        lang -> complete(lang.toString()));

// tests:
final HttpRequest request =
    HttpRequest.GET("/")
        .addHeader(
            AcceptLanguage.create(
                Language.create("en-US").withQValue(1f),
                Language.create("en").withQValue(0.7f),
                LanguageRanges.ALL.withQValue(0.1f),
                Language.create("de-DE").withQValue(0.5f)));

testRoute(enRoute).run(request).assertEntity("en-US");
testRoute(deHuRoute).run(request).assertEntity("de-DE");