Add form kitchen sink example.

This commit is contained in:
Sergio Benitez 2016-09-28 19:31:26 -07:00
parent 23808d00bc
commit 6fe2f51332
4 changed files with 121 additions and 1 deletions

View File

@ -23,5 +23,5 @@ members = [
"examples/stream", "examples/stream",
"examples/json", "examples/json",
"examples/handlebars_templates", "examples/handlebars_templates",
"examples/form_types", "examples/form_kitchen_sink",
] ]

View File

@ -0,0 +1,9 @@
[package]
name = "form_kitchen_sink"
version = "0.0.1"
authors = ["Sergio Benitez <sb@sergio.bz>"]
workspace = "../../"
[dependencies]
rocket = { path = "../../lib" }
rocket_codegen = { path = "../../codegen" }

View File

@ -0,0 +1,62 @@
#![feature(plugin, custom_derive)]
#![plugin(rocket_codegen)]
extern crate rocket;
use rocket::{Rocket, Request};
use rocket::response::NamedFile;
use rocket::form::FromFormValue;
use std::io;
// TODO: Make deriving `FromForm` for this enum possible.
#[derive(Debug)]
enum FormOption {
A, B, C
}
impl<'v> FromFormValue<'v> for FormOption {
type Error = &'v str;
fn parse(v: &'v str) -> Result<Self, Self::Error> {
let variant = match v {
"a" => FormOption::A,
"b" => FormOption::B,
"c" => FormOption::C,
_ => return Err(v)
};
Ok(variant)
}
}
#[derive(Debug, FromForm)]
struct FormInput<'r> {
checkbox: bool,
number: usize,
radio: FormOption,
password: &'r str,
textarea: String,
select: FormOption,
}
#[post("/", form = "<sink>")]
fn sink(sink: FormInput) -> String {
format!("{:?}", sink)
}
#[post("/", rank = 2)]
fn sink2(request: &Request) -> &'static str {
println!("form: {:?}", std::str::from_utf8(request.data.as_slice()));
"Sorry, the form is invalid."
}
#[get("/")]
fn index() -> io::Result<NamedFile> {
NamedFile::open("static/index.html")
}
fn main() {
let mut rocket = Rocket::new("localhost", 8000);
rocket.mount("/", routes![index, sink, sink2]);
rocket.launch();
}

View File

@ -0,0 +1,49 @@
<h1>Rocket Form Kitchen Sink</h1>
<form action="/" method="post" accept-charset="utf-8">
<label>Checkbox:
<input type="hidden" name="checkbox" value="off">
<input type="checkbox" name="checkbox" value="on">
</label><br /><br />
<label>Number:
<input name="number" type="number" value="123" />
</label><br /><br />
<label>Password:
<input name="password" type="password" />
</label>
<br /><br />
<label for="radio">Radios:
<label for="a">A
<input type="radio" name="radio" id="a" value="a" />
</label>
<label for="b">B
<input type="radio" name="radio" id="b" value="b" checked />
</label>
<label for="c">C
<input type="radio" name="radio" id="c" value="c" />
</label>
</label>
<br /><br />
<label>Textarea:
<textarea name="textarea" rows="10" cols="50">Write something here.</textarea>
</label>
<br /><br />
<label>Select:
<select name="select">
<option value="a">Value A</option>
<option value="b" selected>Value B</option>
<option value="c">Value C</option>
</select>
</label>
<br /><br />
<label>Submit:
<input type="submit" value="Login">
</label>
<br /><br />
</form>