静态资源中间件
2025年9月2日小于 1 分钟hyperlanewebrustmiddlewarestatic-file
静态资源中间件
use hyperlane::*;
async fn middleware(ctx: Context) {
ctx.set_response_version(HttpVersion::HTTP1_1)
.await
.set_attribute("static_dir_path", "./")
.await;
}
async fn static_middleware(ctx: Context) {
let static_path_opt: Option<&str> = ctx.try_get_attribute("static_dir_path").await;
let static_path: &str = static_path_opt.expect("attribute static_dir_path not found");
let path: String = ctx.get_request_path().await;
let file_path: String = format!("{static_path}{path}");
let file_extension: String = FileExtension::get_extension_name(&file_path);
let content_type: &'static str = FileExtension::parse(&file_extension).get_content_type();
let content_type: String = ContentType::format_content_type_with_charset(content_type, UTF8);
ctx.set_response_header(CONTENT_TYPE, content_type).await;
let file_data_opt: Option<String> = tokio::fs::read_to_string(&file_path).await.ok();
ctx.set_attribute("static_file_data", file_data_opt).await;
}
async fn response_middleware(ctx: Context) {
let static_file_data_opt: Option<String> = ctx
.try_get_attribute("static_file_data")
.await
.expect("attribute static_file_data not found");
let _ = ctx
.set_response_body(static_file_data_opt.unwrap_or_default())
.await
.send()
.await;
}
#[tokio::main]
async fn main() {
Server::new()
.await
.request_middleware(middleware)
.await
.request_middleware(static_middleware)
.await
.response_middleware(response_middleware)
.await
.run()
.await
.unwrap()
.wait()
.await
}