Skip to content

Instantly share code, notes, and snippets.

@masakielastic
Last active June 22, 2025 18:45
Show Gist options
  • Select an option

  • Save masakielastic/725ea848216d0cb7e29c6840641ea53c to your computer and use it in GitHub Desktop.

Select an option

Save masakielastic/725ea848216d0cb7e29c6840641ea53c to your computer and use it in GitHub Desktop.
axum HTTP/1 サーバーで HTML を表示する(tower_http 使用)
[package]
name = "axum-static"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.8.4"
tokio = { version = "1.0", features = ["full"] }
tower-http = { version = "0.6", features = ["fs"] }
use axum::{
extract::Path,
response::Html,
routing::get,
Router,
};
use std::fs;
use tower_http::services::ServeDir;
#[tokio::main]
async fn main() {
// HTMLファイルを読み込むハンドラ
async fn serve_html() -> Html<String> {
match fs::read_to_string("public/index.html") {
Ok(content) => Html(content),
Err(_) => Html("<h1>Error: public/index.html not found</h1><p>Please create a public/index.html file.</p>".to_str>
}
}
// 指定されたHTMLファイルを読み込むハンドラ
async fn serve_html_file(Path(filename): Path<String>) -> Html<String> {
// .htmlが付いていない場合は追加
let filename = if filename.ends_with(".html") {
filename
} else {
format!("{}.html", filename)
};
let file_path = format!("public/{}", filename);
match fs::read_to_string(&file_path) {
Ok(content) => Html(content),
Err(_) => Html(format!("<h1>Error: {} not found</h1><p>Please create the file in the public directory.</p>", file>
}
}
// ルーターを作成
let app = Router::new()
.route("/", get(serve_html))
// HTMLファイル専用ルート(.htmlなしでもアクセス可能)
.route("/{filename}", get(serve_html_file))
// 静的ファイル(CSS、JS、画像など)を配信
.nest_service("/static", ServeDir::new("public"));
// サーバーを起動
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
.await
.unwrap();
println!("Server running on http://localhost:3000");
println!("Place your HTML files in the 'public' directory");
axum::serve(listener, app)
.await
.unwrap();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment