From e148271a77a45b7482a5b200a9363c36b4a2fc48 Mon Sep 17 00:00:00 2001 From: Timothy Warren Date: Wed, 27 Feb 2019 12:49:50 -0500 Subject: [PATCH] finish web server version of gcd example --- iron-gcd/Cargo.toml | 2 ++ iron-gcd/src/main.rs | 63 ++++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 63 insertions(+), 2 deletions(-) diff --git a/iron-gcd/Cargo.toml b/iron-gcd/Cargo.toml index 665ab6f..59778f9 100644 --- a/iron-gcd/Cargo.toml +++ b/iron-gcd/Cargo.toml @@ -5,7 +5,9 @@ authors = ["Timothy Warren "] 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" + diff --git a/iron-gcd/src/main.rs b/iron-gcd/src/main.rs index bd23b6f..cbb21df 100644 --- a/iron-gcd/src/main.rs +++ b/iron-gcd/src/main.rs @@ -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 { @@ -21,10 +30,60 @@ fn get_form(_request: &mut Request) -> IronResult { GCD Calculator
- +
"#); Ok(response) } + +fn post_gcd(request: &mut Request) -> IronResult { + let mut response = Response::new(); + + let form_data = match request.get_ref::() { + 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 {}\n", numbers, d) + ); + + Ok(response) +}