첨부 실행 코드는 나눔고딕코딩 폰트를 사용합니다.
------------------------------------------------------------------------------------------------------------------------------------------------------
728x90
728x170

■ Actix Web 프레임워크를 사용해 BMI 판정 웹 서버를 만드는 방법을 보여준다.

test_server.zip
0.03MB

▶ Cargo.toml

[package]
name = "test_server"
version = "0.1.0"
edition = "2021"

[dependencies]
actix-web = "3"
serde = "1.0"

 

▶ src/main.rs

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)));
}
728x90
그리드형(광고전용)
Posted by icodebroker
,