Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

自定义中间件

实现步骤

1. 定义中间件 struct

#![allow(unused)]
fn main() {
#[derive(Default)]
pub struct RequestLoggingMiddleware;
}

2. 实现 IMiddleware

#![allow(unused)]
fn main() {
use std::ops::ControlFlow;

#[async_trait]
impl IMiddleware for RequestLoggingMiddleware {
    async fn invoke(&self, ctx: &mut dyn IHttpContext) -> Result<ControlFlow<()>> {
        tracing::info!("→ {} {}", ctx.request().method(), ctx.request().path());
        Ok(ControlFlow::Continue(()))
    }

    async fn after(&self, ctx: &mut dyn IHttpContext) -> Result<()> {
        // `after` 在 Handler 执行后运行,可记录状态码或追加响应头
        tracing::info!("← {} {}", ctx.response().status(), ctx.request().path());
        Ok(())
    }
}
}

3. 注册

#![allow(unused)]
fn main() {
use webx::MiddlewareSpec;

Host::builder()
    // 默认 AfterAuth 槽
    .use_middleware(MiddlewareSpec::new::<RequestLoggingMiddleware>())
    .build();
}

MiddlewareSpec::new 的默认槽位是 MiddlewareSlot::AfterAuth:中间件在 JWT 认证之后运行, 因此 ctx.claims() 能拿到已登录主体(框架自带的 RequestTracing 就是靠这一点记录真实用户)。 需要更早/更晚的位置时用 .at(slot),需要构造参数时用 MiddlewareSpec::factory(..):

#![allow(unused)]
fn main() {
use webx::{MiddlewareSlot, MiddlewareSpec};

Host::builder()
    .use_middleware(MiddlewareSpec::new::<PreflightAudit>().at(MiddlewareSlot::BeforeCors))
    .use_middleware(MiddlewareSpec::new::<TenantGuard>())   // AfterAuth:能读身份
    .use_middleware(
        MiddlewareSpec::factory(|| Arc::new(Fallback::new()) as Arc<dyn IMiddleware>)
            .at(MiddlewareSlot::AfterSpa),
    )
    .build();
}

也可以注册到 DI 容器(svc.add_middleware::<T>())——这类中间件同样进入默认的 AfterAuth 槽,排在 builder 注册的中间件之后。完整顺序见中间件编排策略。

封装为可复用组件

将中间件 + 配置 + 注册逻辑封装为扩展方法:

#![allow(unused)]
fn main() {
// 在你的 crate 中
pub trait HostBuilderExt {
    fn use_tenant_resolver(self, resolver: Arc<TenantResolver>) -> Self;
}

impl HostBuilderExt for HostBuilder {
    fn use_tenant_resolver(self, resolver: Arc<TenantResolver>) -> Self {
        // `tenant_middleware(resolver) -> Arc<dyn IMiddleware>`
        self.use_middleware(MiddlewareSpec::factory(move || {
            tenant_middleware(Arc::clone(&resolver))
        }))
    }
}
}

这样消费方只需 .use_tenant_resolver(resolver) 一行启用。

工厂函数模式

需要构造参数的中间件用工厂函数 + MiddlewareSpec::factory 挂载:

#![allow(unused)]
fn main() {
Host::builder().use_middleware(MiddlewareSpec::factory(move || {
    Arc::new(TenantMiddleware::new(Arc::clone(&resolver))) as Arc<dyn IMiddleware>
}))
}

也可以直接注册到 register() 的 ServiceCollection:

#![allow(unused)]
fn main() {
svc.add(ServiceLifetime::Singleton, move |_| {
    Arc::new(TenantMiddleware::new(Arc::clone(&resolver))) as Arc<dyn IMiddleware>
})
}

框架自带的 JWT 中间件同样由工厂函数产出:

#![allow(unused)]
fn main() {
pub fn jwt_middleware(handler: Arc<dyn IAuthenticationHandler>) -> impl IMiddleware
}

它由 use_authentication() 自动接入管道,通常无需手动注册。

小结

自定义中间件只需 impl IMiddleware + 注册。复杂场景用工厂函数或 Builder 扩展方法封装。

下一节:中间件编排策略

统一 Next 语义

旧式 invoke/after 中间件无需改动(默认桥接)。需要包裹剩余链路时——超时、重试、 熔断、耗时统计——改成 continuation 风格,并声明 continuation() -> true:

#![allow(unused)]
fn main() {
#[async_trait]
impl IMiddleware for ExecutionTimeout {
    async fn invoke(&self, _ctx: &mut dyn IHttpContext) -> Result<ControlFlow<()>> {
        Ok(ControlFlow::Continue(())) // continuation 风格下由 invoke_next 驱动
    }

    fn continuation(&self) -> bool { true }

    async fn invoke_next(&self, ctx: &mut dyn IHttpContext, next: NextStage) -> Result<()> {
        match tokio::time::timeout(self.timeout, next.run(ctx)).await {
            Ok(result) => result,
            Err(_) => { ctx.response_mut().set_status(504); Ok(()) }
        }
    }
}
}
  • next.run(ctx).await 推进剩余中间件与 Handler;不调用即短路(等价旧式 Break)。
  • 内置 TimeoutMiddleware::new(Duration) 即此实现,可直接注册。
  • 默认管道(无 continuation 阶段)仍走零分配旧循环;注册新式中间件后整条管道切换到 continuation 执行器(每阶段一个 boxed future,配置期一次性取舍)。
  • 详细语义、错误/after 顺序、迁移表与验收:见 中间件统一 Next 语义。