[RUST/ACTIX-WEB] Actix Web 프레임워크를 사용해 BMI 판정 웹 서버 만들기
■ Actix Web 프레임워크를 사용해 BMI 판정 웹 서버를 만드는 방법을 보여준다. ▶ Cargo.toml
1 2 3 4 5 6 7 8 9 10 |
[package] name = "test_server" version = "0.1.0" edition = "2021" [dependencies] actix-web = "3" serde = "1.0" |
▶ src/main.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 |
use std::io; use actix_web::web; use serde; const SERVER_ADDRESS : &str = "127.0.0.1:8888"; #[actix_web::main] async fn main() -> io::Result<()> { println!("[서버] http://{}/", SERVER_ADDRESS); actix_web::HttpServer::new ( || { actix_web::App::new() .service(index) .service(calculate) } ) .bind(SERVER_ADDRESS)? .run() .await } #[actix_web::get("/")] async fn index(_ : actix_web::HttpRequest) -> Result<actix_web::HttpResponse, actix_web::Error> { return Ok ( actix_web::HttpResponse::Ok() .content_type("text/html; charset=utf-8") .body ( r#" <html> <body> <h1>BMI 계산 및 비만도 판정</h1> <form action='calculate'> <div>키 : <div><label><input name='height' value='160'></label></div></div> <div>몸무게 : <div><label><input name='weight' value='70'></label></div></div> <div><label><input type='submit' value='확인'></label></div> </form> </body> </html> "# ) ); } #[derive(serde::Deserialize, Debug)] pub struct BMI { height : f64, weight : f64, } #[actix_web::get("/calculate")] async fn calculate(bmi : web::Query<BMI>) -> Result<actix_web::HttpResponse, actix_web::Error> { println!("{:?}", bmi); let temporary_height : f64 = bmi.height / 100.0; let bmi : f64 = bmi.weight / (temporary_height * temporary_height); let bmi_percentage : f64 = (bmi / 22.0) * 100.0; return Ok(actix_web::HttpResponse::Ok() .content_type("text/html; charset=utf-8") .body(format!("<h3>BMI = {:.1}, 비만율 = {:.0}%</h3>", bmi, bmi_percentage))); } |
test_server.zip