finish web server version of gcd example

This commit is contained in:
Timothy Warren 2019-02-27 12:49:50 -05:00
parent 2366827a16
commit e148271a77
2 changed files with 63 additions and 2 deletions

View File

@ -5,7 +5,9 @@ authors = ["Timothy Warren <tim@timshomepage.net>"]
edition = "2018"
[dependencies]
gcd = { path = "../gcd", version = "0.1.0" }
iron = "0.5.1"
mime = "0.2.3"
router = "0.5.1"
urlencoded = "0.5.0"

View File

@ -1,15 +1,24 @@
extern crate gcd;
extern crate iron;
extern crate router;
extern crate urlencoded;
#[macro_use] extern crate mime;
use gcd::gcd;
use iron::prelude::*;
use iron::status;
use router::Router;
use std::str::FromStr;
use urlencoded::UrlEncodedBody;
fn main() {
let mut router = Router::new();
router.get("/", get_form, "root");
router.post("/gcd", post_gcd, "gcd");
println!("Serving on http://localhost:3000...");
Iron::new(get_form).http("localhost:3000").unwrap();
Iron::new(router).http("localhost:3000").unwrap();
}
fn get_form(_request: &mut Request) -> IronResult<Response> {
@ -21,10 +30,60 @@ fn get_form(_request: &mut Request) -> IronResult<Response> {
<title>GCD Calculator</title>
<form action="/gcd" method="post">
<input type="number" min="0" name="n" />
<input type="number" min="0" name="m" />
<input type="number" min="0" name="n" />
<button type="submit">Compute GCD</button>
</form>
"#);
Ok(response)
}
fn post_gcd(request: &mut Request) -> IronResult<Response> {
let mut response = Response::new();
let form_data = match request.get_ref::<UrlEncodedBody>() {
Err(e) => {
response.set_mut(status::BadRequest);
response.set_mut(format!("Error parsing form data: {:?}\n", e));
return Ok(response)
},
Ok(map) => map,
};
let unparsed_numbers = match form_data.get("n") {
None => {
response.set_mut(status::BadRequest);
response.set_mut(format!("form data has no 'n' parameter\n"));
return Ok(response);
},
Some(nums) => nums,
};
let mut numbers = Vec::new();
for unparsed in unparsed_numbers {
match u64::from_str(&unparsed) {
Err(_) => {
response.set_mut(status::BadRequest);
response.set_mut(format!("Value for 'n' parameter not a number: {:?}\n", unparsed));
return Ok(response);
},
Ok(n) => {
numbers.push(n);
},
}
}
let mut d = numbers[0];
for m in &numbers[1..] {
d = gcd(d, *m);
}
response.set_mut(status::Ok);
response.set_mut(mime!(Text/Html; Charset=Utf8));
response.set_mut(
format!("The greatest common divisor of the numbers {:?} is <B>{}</b>\n", numbers, d)
);
Ok(response)
}