gcd web p2

This commit is contained in:
Sangeeth Sudheer 2022-08-16 15:03:13 +05:30
parent dd87f1bd5d
commit dd6cdbee6d

View File

@ -1,22 +1,45 @@
use actix_web::{web, App, HttpResponse, HttpServer};
use serde::Deserialize;
#[derive(Deserialize)]
struct GcdParams {
a: u64,
b: u64,
}
fn gcd(mut a: u64, mut b: u64) -> u64 {
while a > 0 {
if a < b {
let temp = a;
a = b;
b = temp;
}
a = a % b;
}
b
}
fn main() {
let server = HttpServer::new(|| {
App::new()
.route("/", web::get().to(get_index))
.route("/gcd", web::post().to(post_gcd))
});
println!("Serving on http://localhost:3300");
server.bind("127.0.0.1:3300").expect("error binding server to address")
.run().expect("error running server")
server
.bind("127.0.0.1:3300")
.expect("error binding server to address")
.run()
.expect("error running server")
}
fn get_index() -> HttpResponse {
HttpResponse::Ok()
.content_type("text/html")
.body(
r#"
HttpResponse::Ok().content_type("text/html").body(
r#"
<title>GCD Calculator</title>
<form action="/gcd" method="post">
<input type="text" name="a" />
@ -24,5 +47,24 @@ fn get_index() -> HttpResponse {
<button type="submit">Compute GCD</button>
</form>
"#,
)
}
)
}
fn post_gcd(form: web::Form<GcdParams>) -> HttpResponse {
if form.a == 0 || form.b == 0 {
return HttpResponse::BadRequest()
.content_type("text/html")
.body("Computing the GCD with 0 is boring");
}
let response_text = format!(
"The greatest common divisor of {} and {} is {}",
form.a,
form.b,
gcd(form.a, form.b)
);
HttpResponse::Ok()
.content_type("text/html")
.body(response_text)
}