超时中间件
2025年8月22日小于 1 分钟hyperlanewebrustmiddlewaretimeout
提示
hyperlane
框架支持超时中间件,用于处理请求超时的情况。
超时中间件
use hyperlane::{
tokio::{
spawn,
time::{sleep, timeout},
},
*,
};
use std::time::Duration;
async fn http_version_middleware(ctx: Context) {
ctx.set_response_version(HttpVersion::HTTP1_1).await;
}
async fn timeout_middleware(ctx: Context) {
spawn(async move {
timeout(Duration::from_millis(100), async move {
ctx.set_response_status_code(504)
.await
.set_response_body("timeout")
.await
.send()
.await
.unwrap();
ctx.aborted().await;
})
.await
.unwrap();
});
}
async fn index(ctx: Context) {
sleep(Duration::from_secs(1)).await;
ctx.set_response_status_code(200)
.await
.set_response_body("Hello, world!")
.await;
}
async fn response_middleware(ctx: Context) {
ctx.send().await.unwrap();
}
#[tokio::main]
async fn main() {
Server::new()
.request_middleware(http_version_middleware)
.await
.request_middleware(timeout_middleware)
.await
.response_middleware(response_middleware)
.await
.route("/", index)
.await
.run()
.await
.unwrap();
}