37 lines
1.0 KiB
Rust
37 lines
1.0 KiB
Rust
use rocket::request::FromParam;
|
|
use phf::phf_map;
|
|
|
|
|
|
pub struct RequestLanguage {
|
|
pub language: String,
|
|
pub simple_language: String,
|
|
}
|
|
|
|
|
|
fn find_key_for_value<'a>(map: &'a phf::Map<&'a str, &'a str>, value: &str) -> Option<&'a str> {
|
|
map.into_iter()
|
|
.find_map(|(key, &val)| if val == value { Some(*key) } else { None })
|
|
}
|
|
|
|
static LANG_TO_CODES: phf::Map<&'static str, &'static str> = phf_map! {
|
|
"cs" => "cs-CZ",
|
|
"en" => "en-US",
|
|
};
|
|
|
|
impl<'r> FromParam<'r> for RequestLanguage {
|
|
type Error = &'r str;
|
|
|
|
fn from_param(param: &'r str) -> Result<Self, Self::Error> {
|
|
match LANG_TO_CODES.get(param) {
|
|
Some(val) => Ok(RequestLanguage {
|
|
language: val.to_string(),
|
|
simple_language: find_key_for_value(&LANG_TO_CODES, val).unwrap_or("un").to_string(),
|
|
}),
|
|
None => Ok(RequestLanguage {
|
|
language: LANG_TO_CODES["en"].to_string(),
|
|
simple_language: "en".to_string(),
|
|
}),
|
|
}
|
|
}
|
|
}
|