The redirect from /
With the axum feature, redirect_to_locale answers GET / with a redirect to the page in the visitor's language.
redirect_to_locale
pub trait LocaleRouterExt<St>: Sized {
fn redirect_to_locale<L: Locale + Send + Sync>(self, home: Route<L>) -> Self;
}
impl<St: Clone + Send + Sync + 'static> LocaleRouterExt<St> for Router<St> { /* ... */ }LocaleRouterExt extends axum's Router with redirect_to_locale, which adds a route for GET /. It reads Accept-Language, picks the language with negotiate, and redirects to home in that language. It comes with the axum feature of hypersig_i18n, which is on by default. With default-features = false, the trait does not exist.
let app = pages(Router::new()).redirect_to_locale(HOME);The HTTP exchange
For a browser set to Japanese, with HOME at /{lang}:
GET / HTTP/1.1
Accept-Language: ja-JP,ja;q=0.9,en;q=0.8
HTTP/1.1 307 Temporary Redirect
location: /ja
vary: accept-language
content-length: 0The browser then requests /ja. A request without Accept-Language gets location: /en, the first variant.
307 Temporary Redirectkeeps/as the address to come back to. A browser or a search engine does not record/jain its place, as it would for a308, so the next visit to/is negotiated again.vary: accept-languagetells caches that the response differs by that header, so a cache does not send a reader of English to/ja.
The route it takes
home is a Route<L> whose only parameter is the language, because / holds nothing else to fill a parameter with. L is inferred from the route, so a route with more parameters, such as Route<(Lang, i32)>, makes L the tuple, which is not a Locale, and is E0277:
use axum::Router;
use hypersig::Route;
use hypersig_i18n::LocaleRouterExt;
hypersig::routes! {
fn pages(Router<()>);
const MEMBER: Route<(Lang, i32)> = "/{lang}/members/{id}" => member;
}
// error[E0277]: the trait bound `(Lang, i32): Locale` is not satisfied
let app: Router = pages(Router::new()).redirect_to_locale(MEMBER);What stays unchecked
- The types do not check that no other route serves
/. If two routes handleGET /, axum panics when the router is built, withOverlapping method route. - The redirect covers
/alone. A path without a language, such as/members/7, gets a 404 unless a handler of your own sends it on, as Choosing the language shows.
A complete example
A home page in English and Japanese, with the redirect from /. The requests at the end check the exchange above.
// `Lang` is a `Locale` enum with the variants `En` and `Ja`, and `ByLang` its text struct.
use axum::Router;
use axum::body::Body;
use axum::http::{Request, StatusCode, header};
use hypersig::html::h1;
use hypersig::{Page, Route, Signals};
use hypersig_i18n::LocaleRouterExt;
use tower::ServiceExt as _;
#[derive(Signals, Serialize, Deserialize)]
struct Home {}
hypersig::routes! {
fn pages(Router<()>);
const HOME: Route<Lang> = "/{lang}" => home;
}
async fn home((): (), lang: Lang) -> Page<Home> {
let title = lang.pick(ByLang { en: "Welcome", ja: "ようこそ" });
Page::new(title, Home {}).lang(lang.tag()).child(h1().text(title))
}
fn app() -> Router {
pages(Router::new()).redirect_to_locale(HOME)
}
let request = Request::get("/")
.header(header::ACCEPT_LANGUAGE, "ja-JP,ja;q=0.9,en;q=0.8")
.body(Body::empty())
.unwrap();
let response = app().oneshot(request).await.unwrap();
assert_eq!(response.status(), StatusCode::TEMPORARY_REDIRECT);
assert_eq!(response.headers()[header::LOCATION], "/ja");
assert_eq!(response.headers()[header::VARY], "accept-language");
let request = Request::get("/").body(Body::empty()).unwrap();
let response = app().oneshot(request).await.unwrap();
assert_eq!(response.headers()[header::LOCATION], "/en");Accept-Language, so it cannot redirect by language. Such a site serves its default language at / and links to the other languages from every page with a language switcher.Next
- Alternate pages tells search engines the address of each page in every language.
- Plurals, numbers, and dates writes values in the page's language.