处理器
概述
Handler特征
#[async_trait]
pub trait Handler: Send + Sync + 'static {
async fn call(&self, req: Request) -> Result<Response>;
}内置处理器
静态文件处理器
函数处理器
自定义处理器
处理器组合
Last updated
#[async_trait]
pub trait Handler: Send + Sync + 'static {
async fn call(&self, req: Request) -> Result<Response>;
}Last updated
use silent::prelude::*;
let route = Route::new("static")
.get(StaticFileHandler::new("static_files"));use silent::prelude::*;
async fn hello(_req: Request) -> Result<Response> {
Ok(Response::text("Hello World!"))
}
let route = Route::new("").get(hello);use silent::prelude::*;
pub struct CustomHandler;
#[async_trait]
impl Handler for CustomHandler {
async fn call(&self, req: Request) -> Result<Response> {
// 处理请求逻辑
let body = format!("Received request: {} {}", req.method(), req.uri());
Ok(Response::text(body))
}
}
// 使用自定义处理器
let route = Route::new("").get(CustomHandler);let route = Route::new("")
.middleware(Logger) // 添加日志中间件
.middleware(Auth) // 添加认证中间件
.get(CustomHandler); // 处理器#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn test_my_handler() {
let handler = MyHandler;
let req = Request::default();
let resp = handler.call(req).await.unwrap();
assert_eq!(resp.status(), 200);
}
}