Rocket/examples/forms/src/main.rs

53 lines
1.3 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;
#[cfg(test)] mod tests;
2016-03-30 08:02:21 +00:00
use rocket::request::Form;
use rocket::response::Redirect;
2016-04-04 11:14:18 +00:00
#[derive(FromForm)]
struct UserLogin<'r> {
username: &'r str,
2016-12-31 06:48:31 +00:00
password: String,
age: Result<usize, &'r str>,
}
#[post("/login", data = "<user_form>")]
fn login<'a>(user_form: Form<'a, UserLogin<'a>>) -> Result<Redirect, String> {
let user = user_form.get();
match user.age {
Ok(age) if age < 21 => return Err(format!("Sorry, {} is too young!", age)),
Ok(age) if age > 120 => return Err(format!("Are you sure you're {}?", age)),
Err(e) => return Err(format!("'{}' is not a valid integer.", e)),
Ok(_) => { /* Move along, adult. */ }
};
if user.username == "Sergio" {
2016-12-31 06:48:31 +00:00
match user.password.as_str() {
2016-11-03 18:09:08 +00:00
"password" => Ok(Redirect::to("/user/Sergio")),
2016-03-30 08:02:21 +00:00
_ => Err("Wrong password!".to_string())
}
} else {
Err(format!("Unrecognized user, '{}'.", user.username))
}
}
#[get("/user/<username>")]
2016-04-05 02:02:51 +00:00
fn user_page(username: &str) -> String {
format!("This is {}'s page.", username)
}
2017-02-02 10:16:21 +00:00
pub fn rocket() -> rocket::Rocket {
rocket::ignite()
.mount("/", routes![files::index, files::files, user_page, login])
2017-02-02 10:16:21 +00:00
}
fn main() {
rocket().launch()
}