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

自定义 Endpoint

IEndpoint 接口

#![allow(unused)]
fn main() {
#[async_trait]
pub trait IEndpoint: Send + Sync {
    async fn handle(&self, ctx: &mut dyn IHttpContext) -> Result<()>;
}
}

内置实现

类型用途
RequestEndpoint标准 IRequest → Handler 调度
ControllerEndpoint自定义函数式 endpoint(接受闭包)
StaticJsonEndpoint返回固定 JSON
StaticHtmlEndpoint返回固定 HTML
StubEndpointHost::build() 根据 RouteEntry 创建的路由端点,执行授权、参数绑定并调用 Handler

自定义 Endpoint 示例

#![allow(unused)]
fn main() {
pub struct WebhookEndpoint {
    secret: String,
}

#[async_trait]
impl IEndpoint for WebhookEndpoint {
    async fn handle(&self, ctx: &mut dyn IHttpContext) -> Result<()> {
        let signature = ctx.request().header("X-Signature").unwrap_or("");
        if !verify_signature(signature, &self.secret) {
            ctx.response_mut().set_status(401);
            return Ok(());
        }
        // 处理 webhook payload
        ctx.response_mut().set_status(200);
        Ok(())
    }
}
}

注册自定义 Endpoint

Host::build() 会在内部构建路由表,HostBuilder 目前没有公开往路由器里追加 IEndpoint 的接口(Host::router 是私有字段)。因此自定义 IEndpoint 主要作为 框架内部扩展点,而不是应用层 API。

应用层需要「完全掌控响应」时,用下面两种方式之一,二者都是框架的一等能力:

  1. 返回 IActionResult(推荐):路由仍然是普通的 #[get] / #[post] 端点, Handler 把响应类型写成 Response,返回 FileResult / ContentResult / StatusCodeResult 等结果,由结果自己决定状态码、响应头与响应体。 见文件上传与下载。

    #![allow(unused)]
    fn main() {
    #[get("/api/files/{id}/download")]
    impl IRequest<Response> for DownloadFileRequest {}
    }

    需要「空 body + 自定义响应头」(例如 301 Location、401 WWW-Authenticate)时,实现一个 极小的 IActionResult 即可——StatusCodeResult 只带状态码,不带响应头:

    #![allow(unused)]
    fn main() {
    struct Redirect(pub String);
    
    #[async_trait]
    impl IActionResult for Redirect {
        async fn execute(self: Box<Self>, ctx: &mut dyn IHttpContext) -> Result<()> {
            let resp = ctx.response_mut();
            resp.set_status(301);
            resp.set_header("location", &self.0);
            Ok(())
        }
    }
    
    // Handler:Ok(Box::new(Redirect("/api/new-path".into())))
    }
  2. 写中间件:IMiddleware 拿得到 &mut dyn IHttpContext,可以在路由之前 短路请求、直接写响应体,例如 /robots.txt、/sitemap.xml 这类非 API 路径。

何时使用

场景推荐
标准 REST APIRequestEndpoint(默认,无需自定义)
文件下载 / 自定义状态码与响应头Response + FileResult / ContentResult
Webhook 验签自定义 IEndpoint(框架内扩展)或中间件
固定响应(健康检查)StaticJsonEndpoint
服务端渲染 HTMLStaticHtmlEndpoint 或中间件

小结

大多数场景使用默认 RequestEndpoint 即可;需要掌控响应时返回 IActionResult, 需要在路由之前拦截时写中间件。

下一节:样式与约定封装