Rocket/examples/forms/src/main.rs

48 lines
1.1 KiB
Rust
Raw Normal View History

2016-04-04 11:14:18 +00:00
#![feature(plugin, custom_derive)]
2016-09-09 03:38:58 +00:00
#![plugin(rocket_codegen)]
extern crate rocket;
2016-03-30 08:02:21 +00:00
mod files;
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-09-04 11:06:28 +00:00
#[post("/login", form = "<user>")]
2016-03-30 08:02:21 +00:00
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-09-04 11:06:28 +00:00
#[post("/user/<username>")]
2016-04-05 02:02:51 +00:00
fn user_page(username: &str) -> String {
format!("This is {}'s page.", username)
}
fn main() {
rocket::ignite()
.mount("/", routes![files::index, files::files, user_page, login])
.launch();
}