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

内置中间件一览

框架自带中间件

中间件启用方式职责
错误处理自动(host 请求循环)Error → RFC 9457 响应
RequestId自动生成 X-Request-Id
SecurityHeaders自动X-Frame-Options 等
CORSuse_cors(config)跨域
JWT Authuse_authentication()Bearer Token 认证
Resource Auth自动(端点上的 #[authorize])基于端点元数据的授权
RateLimit配置 RateLimit.enabled请求速率限制
SPAuse_spa("wwwroot")静态文件托管
RequestTracing需手动 use_middleware(MiddlewareSpec::new::<RequestTracing>())请求日志、注入 x-trace-id,并写入请求上下文(Handler 用 RequestContext::trace_id() 读取)
Timing需手动 use_middleware(MiddlewareSpec::new::<TimingMiddleware>())注入 x-request-count
Compression需手动 use_middleware(MiddlewareSpec::new::<CompressionMiddleware>())Gzip 压缩

CORS

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

Host::builder()
    .use_cors(CorsConfig {
        origins: vec!["http://localhost:3000".into()],
        ..Default::default()
    })
}

或从 appsettings.json 的 Cors 节自动加载。

JWT 认证

#![allow(unused)]
fn main() {
Host::builder().use_authentication()
}

use_authentication() 注册 jwt_middleware 并从 Jwt.Secret 读取密钥。管道顺序见 中间件编排策略,授权语义见 认证与授权。

SPA 托管

#![allow(unused)]
fn main() {
Host::builder().use_spa("wwwroot")
}

非 API 路径 fallback 到 index.html,支持前端 History 路由。

速率限制

在 appsettings.json 的 RateLimit 节启用即自动接入;也可手动提供配置:

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

Host::builder().use_middleware(MiddlewareSpec::factory(|| {
    Arc::new(RateLimitMiddleware::from_config(&RateLimitSection {
        enabled: true,
        requests_per_second: 10.0,
        burst_size: 20,
        ..Default::default()
    })) as Arc<dyn IMiddleware>
}))
}

RateLimitMiddleware 没有 Default,必须用 new(requests_per_second, burst_size) 或 from_config(...) 构造。按客户端地址限流:地址取自 ClientInfo 中间件的解析结果(未安装 ClientInfo 中间件时为连接对端地址);是否采信 X-Forwarded-For 由 ClientInfo 配置节统一决定, RateLimit 节不再单独配置转发头。

小结

大部分生产中间件通过 HostBuilder 方法一行启用,无需手动组装。RequestTracing、Timing、 Compression 需要用 use_middleware 显式接入。

下一节:自定义中间件