gcd web p2
This commit is contained in:
parent
dd87f1bd5d
commit
dd6cdbee6d
@ -1,22 +1,45 @@
|
|||||||
use actix_web::{web, App, HttpResponse, HttpServer};
|
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() {
|
fn main() {
|
||||||
let server = HttpServer::new(|| {
|
let server = HttpServer::new(|| {
|
||||||
App::new()
|
App::new()
|
||||||
.route("/", web::get().to(get_index))
|
.route("/", web::get().to(get_index))
|
||||||
|
.route("/gcd", web::post().to(post_gcd))
|
||||||
});
|
});
|
||||||
|
|
||||||
println!("Serving on http://localhost:3300");
|
println!("Serving on http://localhost:3300");
|
||||||
|
|
||||||
server.bind("127.0.0.1:3300").expect("error binding server to address")
|
server
|
||||||
.run().expect("error running server")
|
.bind("127.0.0.1:3300")
|
||||||
|
.expect("error binding server to address")
|
||||||
|
.run()
|
||||||
|
.expect("error running server")
|
||||||
}
|
}
|
||||||
|
|
||||||
fn get_index() -> HttpResponse {
|
fn get_index() -> HttpResponse {
|
||||||
HttpResponse::Ok()
|
HttpResponse::Ok().content_type("text/html").body(
|
||||||
.content_type("text/html")
|
r#"
|
||||||
.body(
|
|
||||||
r#"
|
|
||||||
<title>GCD Calculator</title>
|
<title>GCD Calculator</title>
|
||||||
<form action="/gcd" method="post">
|
<form action="/gcd" method="post">
|
||||||
<input type="text" name="a" />
|
<input type="text" name="a" />
|
||||||
@ -24,5 +47,24 @@ fn get_index() -> HttpResponse {
|
|||||||
<button type="submit">Compute GCD</button>
|
<button type="submit">Compute GCD</button>
|
||||||
</form>
|
</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)
|
||||||
}
|
}
|
Loading…
Reference in New Issue
Block a user