I18n fairing

This commit is contained in:
Bat 2018-06-15 14:55:14 +01:00
parent c9b4c40fa1
commit 327768d3fe
2 changed files with 44 additions and 0 deletions

42
src/i18n.rs Normal file
View File

@ -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<Rocket, Rocket> {
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("-", "_")));
}
}

View File

@ -39,6 +39,7 @@ use std::env;
mod activity_pub; mod activity_pub;
mod db_conn; mod db_conn;
mod i18n;
mod models; mod models;
mod schema; mod schema;
mod routes; mod routes;
@ -128,5 +129,6 @@ fn main() {
]) ])
.manage(init_pool()) .manage(init_pool())
.attach(Template::fairing()) .attach(Template::fairing())
.attach(i18n::I18n::new("plume"))
.launch(); .launch();
} }