LoginSignup
1
1

簡単な(30行未満)Webサーバーの作り方※コメント沢山書いた

Last updated at Posted at 2023-03-16

30行未満で書くぞ。詳しいことはコメント参照

main.rs
use hyper::service::{make_service_fn, service_fn};
use hyper::{Body, Request, Response, Server};

//HTTPリクエストを処理する関数handleを定義
//Requestを引数に取り、Responseを返す非同期関数
async fn handle(_: Request<Body>) -> Result<Response<Body>, hyper::Error> {
    //ResponseオブジェクトのBody 型に変換するために.into()を使用
    Ok(Response::new("Hello, World!".into()))
}

//main関数を非同期として宣言
#[tokio::main]
async fn main() {
    //make_service_fnを使用して、handle関数を呼び出すservice_fnを作成
    let make_svc = make_service_fn(|_conn| async { Ok::<_, hyper::Error>(service_fn(handle)) });
    //サーバーのアドレスとポート番号を定義
    let addr = ([127, 0, 0, 1], 3000).into();
    //Server構造体のインスタンスを作成
    let server = Server::bind(&addr).serve(make_svc);

    println!("アクセス!⇒ http://{}", addr);

    //サーバーの起動中にエラーが発生した場合、エラーを出力
    //server.awaitはサーバーが終了するまで待機する非同期関数
    if let Err(e) = server.await {
        eprintln!("server error: {}", e);
    }
}

Cargo.toml
[dependencies]
hyper = {version = "0.14", features = ["full"]}
tokio = { version = "1", features = ["full"] }

あとはcargo runすればよか!!

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1