Rocket/examples/forms/src/main.rs

49 lines
1.2 KiB
Rust
Raw Normal View History

2016-04-04 11:14:18 +00:00
#![feature(plugin, custom_derive)]
#![plugin(rocket_macros)]
extern crate rocket;
2016-03-30 08:02:21 +00:00
mod files;
use rocket::Rocket;
use rocket::response::Redirect;
2016-04-04 11:14:18 +00:00
#[derive(FromForm)]
struct UserLogin<'r> {
username: &'r str,
password: &'r str,
age: Result<isize, &'r str>,
}
2016-03-30 08:02:21 +00:00
#[route(POST, path = "/login", form = "<user>")]
fn login(user: UserLogin) -> Result<Redirect, String> {
2016-04-04 05:41:31 +00:00
if user.age.is_err() {
let input = user.age.unwrap_err();
return Err(format!("'{}' is not a valid age integer.", input));
}
2016-04-05 02:02:51 +00:00
let age = user.age.unwrap();
if age < 20 {
return Err(format!("Sorry, {} is too young!", age));
2016-04-04 05:41:31 +00:00
}
2016-03-30 08:02:21 +00:00
match user.username {
"Sergio" => match user.password {
2016-04-04 04:53:25 +00:00
"password" => Ok(Redirect::other("/user/Sergio")),
2016-03-30 08:02:21 +00:00
_ => Err("Wrong password!".to_string())
},
_ => Err(format!("Unrecognized user, '{}'.", user.username))
}
}
2016-04-05 02:02:51 +00:00
#[route(GET, path = "/user/<username>")]
fn user_page(username: &str) -> String {
format!("This is {}'s page.", username)
}
fn main() {
2016-03-30 08:02:21 +00:00
let mut rocket = Rocket::new("localhost", 8000);
rocket.mount("/", routes![files::index, files::files, user_page, login]);
rocket.launch();
}