边读rust程序设计这本书边写代码。
今天主要和cargo(换源,包提速),以及actix-web这个库(版本不兼容)鏖战。
清华的源也太慢了,换了中科大的才搞定。
书里的actix-web版本太落后了,编译通过不了,换了actix-web 4.0然后参考官方指南:https://actix.rs/docs/getting-started/,才编译成功。
use actix_web::{web, App, HttpResponse, HttpServer};
use serde::Deserialize;
#[actix_web::main]
async fn main() {
println!("Serving on http://127.0.0.1:3000");
HttpServer::new(|| {
App::new()
.route("/", web::get().to(get_index))
.route("/gcd", web::post().to(post_gcd))
})
.bind(("127.0.0.1", 3000)).expect("bind error!!")
.run()
.await.expect("run error!!");
}
async fn get_index() -> HttpResponse {
HttpResponse::Ok()
.content_type("text/html")
.body(
r#"
<title>GCD Calculator2.0</title>
<form action="/gcd" method="post">
<input type="text" name="n"/>
<input type="text" name="m"/>
<button type="submit">Compute GCD</button>
</form>
"#,
)
}
#[derive(Deserialize)]
struct GcdParameters {
n: u64,
m: u64,
}
async fn post_gcd(form: web::Form<GcdParameters>) -> HttpResponse {
if form.n==0 || form.m == 0 {
return HttpResponse::BadRequest()
.content_type("text/html")
.body("do not input 0!");
}
let response =
format!("the gcd of {} and {} is <b>{}</b>",
form.n, form.m, gcd(form.n, form.m));
return HttpResponse::Ok()
.content_type("text/html")
.body(response);
}
#[test]
fn test_gcd() {
assert_eq!(gcd(14, 15), 1);
assert_eq!(gcd(2*3*5*11*17, 3*7*11*13*19), 3*11);
}
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;
}
return n;
}