Add actix-gcd example, from the tour.
parent
64472e49a7
commit
7f7597a656
@ -0,0 +1,2 @@
|
||||
/target/
|
||||
|
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,12 @@
|
||||
[package]
|
||||
name = "actix-gcd"
|
||||
version = "0.1.0"
|
||||
authors = ["You <you@example.com>"]
|
||||
edition = "2018"
|
||||
|
||||
# See more keys and their definitions at
|
||||
# https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
actix-web = "1.0.8"
|
||||
serde = { version = "1.0", features = ["derive"] }
|
@ -0,0 +1,66 @@
|
||||
use actix_web::{web, App, HttpResponse, HttpServer};
|
||||
|
||||
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:3000...");
|
||||
server
|
||||
.bind("127.0.0.1:3000").expect("error binding server to address")
|
||||
.run().expect("error running server");
|
||||
}
|
||||
|
||||
fn get_index() -> HttpResponse {
|
||||
HttpResponse::Ok()
|
||||
.content_type("text/html")
|
||||
.body(
|
||||
r#"
|
||||
<title>GCD Calculator</title>
|
||||
<form action="/gcd" method="post">
|
||||
<input type="text" name="n"/>
|
||||
<input type="text" name="m"/>
|
||||
<button type="submit">Compute GCD</button>
|
||||
</form>
|
||||
"#,
|
||||
)
|
||||
}
|
||||
|
||||
use serde::Deserialize;
|
||||
#[derive(Deserialize)]
|
||||
struct GcdParameters {
|
||||
n: u64,
|
||||
m: u64,
|
||||
}
|
||||
|
||||
fn post_gcd(form: web::Form<GcdParameters>) -> HttpResponse {
|
||||
if form.n == 0 || form.m == 0 {
|
||||
return HttpResponse::BadRequest()
|
||||
.content_type("text/html")
|
||||
.body("Computing the GCD with zero is boring.");
|
||||
}
|
||||
|
||||
let response =
|
||||
format!("The greatest common divisor of the numbers {} and {} \
|
||||
is <b>{}</b>\n",
|
||||
form.n, form.m, gcd(form.n, form.m));
|
||||
|
||||
HttpResponse::Ok()
|
||||
.content_type("text/html")
|
||||
.body(response)
|
||||
}
|
||||
|
||||
fn gcd(mut n: u64, mut m: u64) -> u64 {
|
||||
assert!(n != 0 && m != 0);
|
||||
while m != 0 {
|
||||
if m < n {
|
||||
let t = m;
|
||||
m = n;
|
||||
n = t;
|
||||
}
|
||||
m = m % n;
|
||||
}
|
||||
n
|
||||
}
|
Loading…
Reference in New Issue