diff --git a/src/i18n.rs b/src/i18n.rs new file mode 100644 index 00000000..6a655593 --- /dev/null +++ b/src/i18n.rs @@ -0,0 +1,42 @@ +use gettextrs::*; +use rocket::{Data, Request, Rocket, fairing::{Fairing, Info, Kind}}; + +const ACCEPT_LANG: &'static str = "Accept-Language"; + +pub struct I18n { + domain: &'static str +} + +impl I18n { + pub fn new(domain: &'static str) -> I18n { + I18n { + domain: domain + } + } +} + +impl Fairing for I18n { + fn info(&self) -> Info { + Info { + name: "Gettext I18n", + kind: Kind::Attach | Kind::Request + } + } + + fn on_attach(&self, rocket: Rocket) -> Result { + bindtextdomain(self.domain, "/usr/local/share/locale"); + textdomain(self.domain); + Ok(rocket) + } + + fn on_request(&self, request: &mut Request, _: &Data) { + let lang = request + .headers() + .get_one(ACCEPT_LANG) + .unwrap_or("en") + .split(",") + .nth(0) + .unwrap_or("en"); + setlocale(LocaleCategory::LcAll, format!("{}.UTF-8", lang.replace("-", "_"))); + } +} diff --git a/src/main.rs b/src/main.rs index 55a49e07..57b316e6 100644 --- a/src/main.rs +++ b/src/main.rs @@ -39,6 +39,7 @@ use std::env; mod activity_pub; mod db_conn; +mod i18n; mod models; mod schema; mod routes; @@ -128,5 +129,6 @@ fn main() { ]) .manage(init_pool()) .attach(Template::fairing()) + .attach(i18n::I18n::new("plume")) .launch(); }