Skip to content

Instantly share code, notes, and snippets.

@masakielastic
Last active June 13, 2025 02:42
Show Gist options
  • Save masakielastic/05c3f76c2c6d2ce53a0294714a5dde77 to your computer and use it in GitHub Desktop.
Save masakielastic/05c3f76c2c6d2ce53a0294714a5dde77 to your computer and use it in GitHub Desktop.
hyper でテキストファイルを表示する HTTP/1 サーバー
[package]
name = "http_server_min"
version = "0.1.0"
edition = "2021"
[dependencies]
tokio = { version = "1.4", features = ["full"] }
hyper = { version = "1.6", features = ["http1", "http2", "server"] }
hyper-util = { version = "0.1", features = ["server-auto", "tokio"] }
http-body-util = "0.1"
bytes = "1"
anyhow = "1"
mime_guess = "2"
use hyper::{
Request, Response, StatusCode,
body::Incoming,
service::service_fn,
};
use hyper_util::rt::{TokioExecutor, TokioIo};
use hyper_util::server::conn::auto::Builder;
use tokio::{fs, net::TcpListener};
use http_body_util::Full;
use std::path::PathBuf;
use bytes::Bytes;
use mime_guess::from_path;
#[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_request);
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 path = PathBuf::from("static/hello.txt");
match fs::read(&path).await {
Ok(contents) => {
let mime = from_path(&path).first_or_octet_stream();
let mut response = Response::new(Full::new(Bytes::from(contents)));
response.headers_mut().insert(
hyper::header::CONTENT_TYPE,
hyper::header::HeaderValue::from_str(mime.as_ref()).unwrap(),
);
Ok(response)
}
Err(_) => {
let mut response = Response::new(Full::new(Bytes::from("404 Not Found")));
*response.status_mut() = StatusCode::NOT_FOUND;
Ok(response)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment