Skip to content

Instantly share code, notes, and snippets.

View andete's full-sized avatar

Joost Yervante Damad andete

View GitHub Profile
#![feature(plugin)]
#![plugin(rocket_codegen)]
extern crate rocket;
#[macro_use]
extern crate log;
use rocket::request::{Outcome, Request, FromRequest};
use rocket::outcome::Outcome::*;
use rocket::response::{NamedFile, Redirect, content};
#[get("/lang/<lang>")]
fn lang(mut cookies: Cookies, referer: Referer, lang: String) -> Result<Redirect> {
let lang:&'static str = Lang::from_str(&lang)?.into();
info!("Setting language to: {}", lang);
cookies.add_private(Cookie::new("lang", lang));
Ok(Redirect::to(&referer.url))
}
struct Referer {
url:String
}
impl<'a, 'r> FromRequest<'a, 'r> for Referer {
type Error = ();
fn from_request(request: &'a Request<'r>) -> Outcome<Referer, ()> {
match request.headers().get_one("Referer") {
Some(r) => Success(Referer { url:r.into() }),
#[get("/lang/<lang>")]
fn lang(mut cookies: Cookies, lang: String) -> Result<Redirect> {
let lang:&'static str = Lang::from_str(&lang)?.into();
info!("Setting language to: {}", lang);
cookies.add_private(Cookie::new("lang", lang));
Ok(Redirect::to("/page"))
}
#[get("/page")]
fn page(lang: Lang) -> content::HTML<String> {
let hello = if lang == Lang::Nl {
"Hallo daar!"
} else {
"Hello there!"
};
content::HTML(format!(
"<html>
<body>
impl<'a, 'r> FromRequest<'a, 'r> for Lang {
type Error = ();
fn from_request(request: &'a Request<'r>) -> Outcome<Lang, ()> {
match request.cookies().get_private("lang") {
Some(r) => {
match Lang::from_str(r.value()) {
Ok(l) => Success(l),
Err(_) => Success(Lang::default()),
}
impl Into<&'static str> for Lang {
fn into(self) -> &'static str {
match self {
Lang::Nl => "nl",
Lang::En => "en",
}
}
}
impl FromStr for Lang {
type Err = Error;
fn from_str(s:&str) -> Result<Self> {
match s {
"nl" => Ok(Lang::Nl),
"en" => Ok(Lang::En),
o => Err(format!("Unsupported language: {}", o).into()),
}
}
}
impl Default for Lang {
fn default() -> Lang {
Lang::Nl
}
}
#[derive(PartialEq)]
enum Lang {
Nl,
En,
}