Last active
June 13, 2025 02:13
-
-
Save masakielastic/087bc00567543800833052494767b91d to your computer and use it in GitHub Desktop.
hyper + tokio による HTTP/1 サーバー
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[package] | |
name = "http_server_min" | |
version = "0.1.0" | |
edition = "2024" | |
[dependencies] | |
tokio = { version = "1.4", features = ["full"] } | |
hyper = { version = "1.6", features = ["http1", "server"] } | |
hyper-util = { version = "0.1", features = ["server-auto", "tokio"] } | |
http-body-util = "0.1" | |
bytes = "1" | |
anyhow = "1" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use hyper::{ | |
Request, Response, | |
body::Incoming, | |
service::service_fn | |
}; | |
use hyper_util::rt::{TokioExecutor, TokioIo}; | |
use hyper_util::server::conn::auto::Builder; | |
use tokio::net::TcpListener; | |
use http_body_util::Full; | |
use bytes::Bytes; | |
#[tokio::main] | |
async fn main() -> anyhow::Result<()> { | |
let listener = TcpListener::bind("127.0.0.1:3000").await?; | |
println!("Listening on http://127.0.0.1:3000"); | |
loop { | |
let (stream, _) = listener.accept().await?; | |
let executor = TokioExecutor::new(); | |
let builder = Builder::new(executor); | |
let io = TokioIo::new(stream); | |
let service = service_fn(handle); | |
tokio::spawn(async move { | |
if let Err(e) = builder.serve_connection(io, service).await { | |
eprintln!("error: {}", e); | |
} | |
}); | |
} | |
} | |
async fn handle_request(_req: Request<Incoming>) -> Result<Response<Full<Bytes>>, hyper::Error> { | |
let body = Full::new(Bytes::from("Hello World!")); | |
Ok(Response::new(body)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment