内置中间件

Silent 提供了多种内置中间件,基于洋葱模型实现,可以直接使用:

1. 请求时间日志

记录每个请求的处理时间,通过洋葱模型在请求前后记录时间戳:

use silent::middleware::RequestTimeLogger;

// 创建基础日志记录器
let logger = RequestTimeLogger::new();

// 可以自定义日志格式和输出方式
let custom_logger = RequestTimeLogger::new()
    .with_format(|method, uri, time| {
        format!("[{}] {} - {}ms", method, uri, time.as_millis())
    });

2. 异常处理

全局异常处理中间件,用于统一处理应用中的错误,支持自定义错误处理逻辑:

use silent::middleware::ExceptionHandler;
use silent::error::Error;

// 基础异常处理器
let exception_handler = ExceptionHandler::new();

// 自定义错误处理逻辑
let custom_handler = ExceptionHandler::new()
    .on_error(|err: Error| async move {
        // 自定义错误响应
        Response::builder()
            .status(err.status_code())
            .json(&serde_json::json!({
                "code": err.status_code().as_u16(),
                "message": err.to_string()
            }))
    });

3. 跨域资源共享 (CORS)

处理跨域请求,支持灵活的CORS配置:

use silent::middleware::{Cors, CorsType};

// 使用默认配置(允许所有源)
let cors = Cors::new();

// 自定义CORS配置
let custom_cors = Cors::new()
    .cors_type(CorsType::Custom)
    .allow_origin("https://example.com")  // 允许的源
    .allow_methods(vec!["GET", "POST"])  // 允许的HTTP方法
    .allow_headers(vec!["Content-Type", "Authorization"])  // 允许的请求头
    .allow_credentials(true)  // 允许携带认证信息
    .max_age(3600);  // 预检请求缓存时间

4. 超时处理

为请求设置超时限制,防止长时间运行的请求占用系统资源:

use silent::middleware::Timeout;
use std::time::Duration;

// 基础超时设置
let timeout = Timeout::new(Duration::from_secs(30));

// 自定义超时配置
let custom_timeout = Timeout::new(Duration::from_secs(30))
    .on_timeout(|_req| async {
        // 自定义超时响应
        Response::builder()
            .status(StatusCode::REQUEST_TIMEOUT)
            .json(&serde_json::json!({
                "error": "请求超时",
                "timeout": 30
            }))
    });

使用示例

use silent::prelude::*;

// 创建应用路由
let route = Route::new("")
    // 添加请求时间日志中间件(最外层,可以记录完整处理时间)
    .hook(RequestTimeLogger::new())
    // 添加异常处理中间件(捕获后续中间件的错误)
    .hook(ExceptionHandler::new())
    // 添加CORS中间件(处理跨域请求)
    .hook(Cors::new()
        .cors_type(CorsType::Custom)
        .allow_origin("https://example.com")
        .allow_methods(vec!["GET", "POST"])
        .allow_credentials(true))
    // 添加超时处理中间件(限制请求处理时间)
    .hook(Timeout::new(Duration::from_secs(30)))
    // 添加路由处理函数
    .get(|_req| async { Ok("Hello World") });

// 启动服务器
Server::new().run(route);

这些内置中间件基于Silent的中间件系统实现,遵循洋葱模型的执行流程。每个中间件都可以:

  1. 在请求处理前执行预处理逻辑

  2. 在请求处理后执行后处理逻辑

  3. 支持灵活的配置选项

  4. 可以组合使用,按注册顺序依次执行

中间件的执行顺序很重要,建议将通用的处理(如日志、异常处理)放在外层,将特定的处理(如认证、授权)放在内层。每个中间件都可以进行自定义配置,以满足特定的应用需求。

Last updated

Was this helpful?