超时中间件
2025/11/10大约 1 分钟hyperlanewebrustmiddlewaretimeout
超时中间件
原生写法
use hyperlane::{
tokio::{
spawn,
time::{sleep, timeout},
},
*,
};
use std::time::Duration;
struct HttpVersionMiddleware;
struct TimeoutMiddleware;
struct IndexRoute;
struct ResponseMiddleware;
impl ServerHook for HttpVersionMiddleware {
async fn new(_ctx: &Context) -> Self {
Self
}
async fn handle(self, ctx: &Context) {
ctx.set_response_version(HttpVersion::HTTP1_1).await;
}
}
impl ServerHook for TimeoutMiddleware {
async fn new(_ctx: &Context) -> Self {
Self
}
async fn handle(self, ctx: &Context) {
let ctx_clone: Context = ctx.clone();
spawn(async move {
timeout(Duration::from_millis(100), async move {
ctx_clone
.set_response_status_code(504)
.await
.set_response_body("timeout")
.await
.send()
.await
.unwrap();
ctx_clone.aborted().await;
})
.await
.unwrap();
});
}
}
impl ServerHook for IndexRoute {
async fn new(_ctx: &Context) -> Self {
Self
}
async fn handle(self, ctx: &Context) {
sleep(Duration::from_secs(1)).await;
ctx.set_response_status_code(200)
.await
.set_response_body("Hello, world!")
.await;
}
}
impl ServerHook for ResponseMiddleware {
async fn new(_ctx: &Context) -> Self {
Self
}
async fn handle(self, ctx: &Context) {
ctx.send().await.unwrap();
}
}
#[tokio::main]
async fn main() {
Server::new()
.await
.request_middleware::<HttpVersionMiddleware>()
.await
.request_middleware::<TimeoutMiddleware>()
.await
.response_middleware::<ResponseMiddleware>()
.await
.route::<IndexRoute>("/")
.await
.run()
.await
.unwrap()
.wait()
.await
}宏写法
use hyperlane::{
tokio::{
spawn,
time::{sleep, timeout},
},
*,
};
use hyperlane_utils::*;
use std::time::Duration;
#[request_middleware(1)]
struct HttpVersionMiddleware;
#[request_middleware(2)]
struct TimeoutMiddleware;
#[route("/")]
struct IndexRoute;
#[response_middleware(1)]
struct ResponseMiddleware;
impl ServerHook for HttpVersionMiddleware {
async fn new(_ctx: &Context) -> Self {
Self
}
#[response_version(HttpVersion::HTTP1_1)]
async fn handle(self, ctx: &Context) {}
}
impl ServerHook for TimeoutMiddleware {
async fn new(_ctx: &Context) -> Self {
Self
}
async fn handle(self, ctx: &Context) {
let ctx_clone: Context = ctx.clone();
spawn(async move {
timeout(Duration::from_millis(100), async move {
ctx_clone
.set_response_status_code(504)
.await
.set_response_body("timeout")
.await
.send()
.await
.unwrap();
ctx_clone.aborted().await;
})
.await
.unwrap();
});
}
}
impl ServerHook for IndexRoute {
async fn new(_ctx: &Context) -> Self {
Self
}
#[response_status_code(200)]
#[response_body("Hello, world!")]
async fn handle(self, ctx: &Context) {
sleep(Duration::from_secs(1)).await;
}
}
impl ServerHook for ResponseMiddleware {
async fn new(_ctx: &Context) -> Self {
Self
}
#[send]
async fn handle(self, ctx: &Context) {}
}
#[tokio::main]
async fn main() {
Server::new().await.run().await.unwrap().wait().await
}加载中...