日本語

Choosing the language

A visitor who opens / is redirected to the page in the language their browser asks for.

negotiate

negotiate reads an Accept-Language value and returns the best language of Locale::ALL. It tries the ranges from the highest q to the lowest, and in the order written where two have the same q. A range first matches a tag equal to it, ignoring case. Next it matches a tag equal to the range with its last subtags dropped, so ja-JP matches ja. Last it matches a tag that starts with the range, so en matches en-US. *, an empty header, and a header with no match give the first language of Locale::ALL.

The redirect from /

With the axum feature, redirect_to_locale responds to GET / with a 307 Temporary Redirect to a route whose only parameter is the language. The response includes Vary: Accept-Language, because the language redirected to can differ between browsers.

use axum::Router;
use hypersig_i18n::{LocaleRouterExt, negotiate};

assert_eq!(negotiate::<Lang>("ja-JP,ja;q=0.9,en;q=0.8"), Lang::Ja);
assert_eq!(negotiate::<Lang>("fr, en;q=0.5"), Lang::En);
assert_eq!(negotiate::<Lang>("de"), Lang::En);

hypersig::routes! {
    fn pages(Router<()>);
    const HOME: Route<Lang> = "/{lang}" => home;
}

// `GET /` answers with a redirect to `/en` or `/ja`.
let _app: Router = pages(Router::new()).redirect_to_locale(HOME);
A site served as static files, such as this one, has no server to read Accept-Language. Such a site puts its default language at the root and links to the others from the header.