Topcoat `[page]` 页面处理器完全指南:模块路由、请求体、路由上下文与组件复用

原创2026-11-11 19:09:231,874 阅读
文章标签:后端Web框架前端

Topcoat #[page] 页面处理器完全指南:模块路由、请求体、路由上下文与组件复用

#<a href="https://link.gitcode.com/i/0d8cdf1bb0dabbcf39c290a5b78b0897" target="_blank">page] 是 Topcoat 中声明“返回页面视图”的处理器宏:它把一段 async fn 变成既能被路由注册、又能在 view! 中当组件调用的构件。本文以官方宏文档 [page.md 为主线,结合 topcoat-router 的宏展开实现、路由构建器与测试用例,逐层讲清路径推导、HTTP 方法声明、函数签名约束、with(...) 路由上下文以及“页面即组件”的复用方式。

一、#[page] 与 #[route] 的分工

两个宏的外观相似,但语义边界清晰:

维度 #[page] #[route]
返回值 Result<impl View>,必须能渲染成页面视图 Result<T>,T 实现 AsyncIntoResponse
默认方法 GET(未声明时) 必须显式声明方法,如 #[route(GET)]
主要用途 渲染 HTML 页面,可被 layout 包裹 返回 JSON、状态码、重定向等 API 响应
宏定义 macro/src/lib.rs 同文件中的 route

#<a href="https://link.gitcode.com/i/310756ec1e2579ebe1f9f8874e341dae" target="_blank">route] 的细节见 [route.md。#[page] 的关键差异在于:它把函数体包装成一个视图渲染流程,并把它注册为 Page(显式路径)或 ModulePage(模块派生路径)。

二、两种注册模型:模块派生 vs 显式路径

#[page] 的属性可以完全为空,也可以携带路径字符串。是否携带路径,决定了宏生成哪一种 trait 实现,从而决定它由谁注册。

2.1 无路径:交给 module_router! 推导

use topcoat::{Result, context::Cx, router::page, view::{View, view}};

// src/app/about.rs,位于 module_router!() 之下,服务 /about
#[page]
async fn about(cx: &Cx) -> Result<impl View> {
    Ok(view! { <h1>"About"</h1> })
}

宏在 crates/topcoat-router/grammar/src/page.rs 中判断路径是否为绝对路径:若不是,则生成 impl ModulePage,并写入 fn module_path(&self) -> &'static str { module_path!() }(见 page.rs)。也就是说,URL 由编译期的模块路径决定,文件名、函数名都不参与 URL 计算。

模块到 URL 的映射规则(详见 module.md):

模块位置 服务路径
app(module_router!() 所在根模块) /
app::about /about
app::blog_posts /blog-posts(静态段转 kebab-case)
app::settings::profile /settings/profile
app::_marketing::pricing /pricing(_ 前缀是分组段,不占 URL)

模块路由由 module_router!() 在链接期收集。宏定义非常短,可以看出它只是把 ModuleRouterBuilder 转成普通 RouterBuilder:

// crates/topcoat-router/src/module.rs
macro_rules! module_router {
    () => {
        ::topcoat::router::RouterBuilder::from(
            ::topcoat::router::ModuleRouterBuilder::new(module_path!()).discover(),
        )
    };
}

因此它依赖 discover feature(topcoat 默认开启),并且要求 module_router!() 必须写在路由树的根模块,因为 ModuleRouterBuilder 需要用 module_path!() 作为前缀来裁剪其它模块路径(router.rs)。

2.2 绝对路径:需要单独注册

// 独立于模块树,服务 /users/{id}
#[page("/users/{id}")]
async fn user_profile(cx: &Cx) -> Result<impl View> {
    Ok(view! { <h1>"User profile"</h1> })
}

绝对路径(以 / 开头)会生成 impl Page,路径直接由 Path::new 常量给出(page.rs)。这类页面不会被 ModuleRouterBuilder::discover_pages 收集,因为该方法只遍历 &'static dyn ModulePage(router.rs)。注册方式有两种:

// 方式一:按函数名逐个注册
pub fn router() -> topcoat::router::Router {
    topcoat::router::module_router!()
        .page(user_profile)
        .build()
}

// 方式二:用 discover 一次性收集所有显式路径页面
use topcoat::router::{RouterBuilderDiscoverExt, module_router};

pub fn router() -> topcoat::router::Router {
    module_router!().discover().build()
}

RouterBuilderDiscoverExt::discover 的实现顺序是 routes → pages → layouts → layers(crates/topcoat/src/router.rs)。因此“模块路由宏 + .discover()”是混合使用两种写法的常见组合。

RouterBuilder::page 的文档也明确:注册顺序不影响 layout 匹配,因为 layout 是按路径前缀选择的(builder.rs)。

2.3 ./ 开头的相对路径:挂在模块路径之下

// src/app/settings.rs,服务 /settings/export
#[page("./export")]
async fn export(cx: &Cx) -> Result<impl View> {
    Ok(view! { <h1>"Export"</h1> })
}

宏对相对路径的处理在 handler_path.rs:去掉开头的 .,把剩下的 /export 交给模块路由拼接。ModuleRouterBuilder::resolve_path 会先算出模块自身路径,再把相对段追加进去(router.rs)。

几个容易忽略的边界:

写法 结果
#[page] 模块路径本身,例如 /settings
#[page("./")] 模块路径加尾斜杠,例如 /settings/
#[page("./export")] /settings/export
#[page("./export/")] /settings/export/(尾斜杠保留)
#[page(".")] 编译错误:a relative path must start with ./``
#[page("../sibling")] 编译错误:a relative path cannot leave the module path; use an absolute path starting with / instead
#[page("export")] 既不是绝对也不是 ./ 相对,会按绝对路径处理,Path::new 在编译期因缺少前导 / 报错

根模块使用 ./ 会 panic,因为根路径没有“带尾斜杠”的形态(router.rs)。

模块路由还支持更细的路径控制:segment!(kind: Param)、segment!(kind: CatchAll)、segment!(rename: "...") 可改写模块段的种类与名字;需要“模块名就是参数名”时用 module_param!(见 module_param.md、segment.md)。示例工程 examples/module-router/src/app.rs 展示了根模块 #[page] 与子模块 #[page] 的对照。

三、声明 HTTP 方法:一个、一组或全部

页面默认只响应 GET。需要其它方法时,把方法写在路径前面,语法与 #[route] 一致:

#[page(POST)]                    // 模块路径 + POST
#[page(POST "/submit")]          // 显式路径 + POST
#[page([GET, POST] "/either")]   // 方法列表
#[page(* "/anything")]           // 任意方法

宏中对应的默认值与生成逻辑在 page.rs:未声明方法时生成 Methods::Only(&<a href="https://link.gitcode.com/i/789995ddf13b06b0c0344844748bb7ba" target="_blank">Method::GET]),声明后由 Methods::to_tokens 输出对应表达式([method.rs)。

几个必须注意的规则:

  • 方法名必须全大写 ASCII。Methods::is_method 逐字节检查 is_ascii_uppercase,所以 #<a href="https://link.gitcode.com/i/baf8120e68db70d29e7e773b05bfab11" target="_blank">page(get)] 会报 expected an uppercase HTTP method, such as GET``([method.rs)。
  • 方法列表不能为空:#[page([])] 报 expected at least one HTTP method。
  • 方法必须写在路径之前:解析顺序是先 Methods::parse_option,再 HandlerPath::parse_option(page.rs)。
  • HEAD 自动复用 GET:构建路由器时,若某端点没有显式 HEAD 路由,会把 HEAD 槽指向 GET(endpoint.rs)。
  • 具体方法优先于 *:* 路由与具体方法路由可共享同一路径,分发时具体方法胜出(builder.rs)。

测试用例直接验证了这些行为(macro/tests/page.rs):

#[tokio::test]
async fn a_page_serves_get_by_default() {
    let router = Router::builder().page(home).build();
    assert_eq!(send_as(&router, "POST", "/").await.0, 405);
}

#[tokio::test]
async fn a_star_page_serves_every_method() {
    let router = Router::builder().page(anything).build();
    for method in ["GET", "POST", "PUT", "DELETE", "PATCH"] {
        assert_eq!(send_as(&router, method, "/anything").await, (200, "<p>anything</p>".into()));
    }
}

未声明的方法返回 405,说明路径匹配成功但方法未注册——这正是排查“页面 405”问题的切入点。

四、处理函数签名:编译期就会拦下的错误

#<a href="https://link.gitcode.com/i/5e584be64e47436b185d96e07bd84eff" target="_blank">page] 对签名有硬性要求,全部由 PageItem::parse 检查([page.rs):

  1. 必须是 async fn,否则报 page functions must be async。
  2. 必须声明返回类型,否则报 page functions must declare a return type。
  3. 第一个参数必须是 cx: &Cx,即使不使用也不能省略;名字必须是 cx,类型必须是 &Cx。
  4. 之后最多一个请求体参数,实现 FromRequest,并可用解构模式,如 Form(input): Form<Search>。
  5. 返回类型必须包含 View,通常写成 Result<impl View>。

语义上的完整签名:

#[page]
async fn handler(
    cx: &Cx,                    // 必需,位置固定在第 1 个
    extractor: impl FromRequest, // 可选,位置固定在第 2 个
) -> Result<impl View> { /* ... */ }

超过一个请求体参数时会报 handler functions cannot take more than one request body parameter(handler_args.rs)。把 cx 放到第二位同样不被接受,错误信息会提示缺少 cx: &Cx。

这些约束不是风格建议,而是因为宏要生成渲染函数:请求体先由 FromRequest::from_request 解析,解析失败时错误会作为视图流的错误一路向上,而不是额外拼一个响应(page.rs)。这保证了 Result<impl View> 的错误处理路径与 layout 的 error_boundary 保持一致。

五、读取请求体:Form、Json 与请求上下文

#[page] 本身不限定提取器类型,任何实现了 FromRequest 的类型都可以放在第二个参数。文档示例使用 Form<T>:

#[page(POST)]
async fn signup(cx: &Cx, Form(input): Form<Signup>) -> Result<impl View> {
    Ok(view! { <h1>"Welcome, " (input.email)</h1> })
}

Form<T> 的行为值得展开,因为它在页面场景中非常常用(content/form.rs):

  • 对 GET / HEAD 请求,从 URI 查询串反序列化;对其它方法,从请求体读取,并要求 Content-Type 为 application/x-www-form-urlencoded(忽略 ; charset=utf-8 等参数和大小写)。
  • 解析失败返回 400 Bad Request,并带上字段路径信息(serde_path_to_error)。
  • 配合 Option<Form<T>> 可让请求体变成可选:GET / HEAD 无查询串时得到 None,其它方法无 Content-Type 时得到 None。
  • 请求体读取遵循 body_limit,超出限制会得到 413 Content Too Large(Bytes::from_request 的实现,见 request.rs)。

因此文档里的“读取请求体”示例实际演示的是查询串读取:

// src/app/contact.rs
#[page]
async fn contact(cx: &Cx, Form(input): Form<Search>) -> Result<impl View> {
    Ok(view! { <main>"searching for " (input.q)</main> })
}

对应的集成测试用 /search?q=topcoat 请求它,并断言输出 <p>searching for topcoat</p>(macro/tests/page.rs)。

若只需要原始字节或字符串,可分别使用 Bytes、String;若要 JSON,换成 Json<T>;若要自定义鉴权、签名校验等逻辑,实现 FromRequest 即可(示例见 request.rs)。

六、路由上下文:with(...) 的初始化时机与覆盖顺序

with(...) 用来给页面附加元数据,典型用途是标题、面包屑、导航高亮分类:

#[page(with(Title("Products")))]
#[page("/products", with(Title("Products")))]
#[page(POST "/described", with(Title("described")), with(presets::tag()))]

语法规则(由 PageAttr 解析):

  • with(...) 位于方法与路径之后,用逗号分隔,可写多个,允许尾随逗号;
  • 与方法或路径之间必须有逗号,缺少逗号会解析失败;
  • 不能有前导逗号;
  • 不认识的关键字(如 title(a))会直接报错;
  • 括号内的表达式按原样保留 token,因此 with(a, b; c) 这类“不是完整表达式”的内容也能通过语法分析(route_context.rs)。

6.1 生成方式与覆盖顺序

宏为每个 with(...) 生成一次 ContextMap::insert,按书写顺序插入(route_context.rs)。由于上下文按类型存储且新值遮蔽旧值,后面的同类型条目会覆盖前面的。测试明确验证了这一点:

#[page("/retitled", with(Title("first")), with(Title("second")))]
async fn retitled(cx: &Cx) -> Result<impl View> { /* ... */ }

#[test]
fn a_later_context_value_shadows_an_earlier_one() {
    let context = Page::context(&retitled);
    assert_eq!(context.get::<Title>(), Some(&Title("second")));
    let titles: Vec<_> = context.iter::<Title>().collect();
    assert_eq!(titles, [&Title("second"), &Title("first")]);
}

注意 iter::<Title>() 依然能访问被遮蔽的旧值且顺序为“最近优先”,这使外层的 layout 可以用 iter_context::<Crumb>(cx) 汇总整条面包屑链(见 context.md)。

6.2 为什么 layout 能在页面运行前读到标题

with(...) 的值在构建路由器时就初始化好,而不是等页面函数执行。因此外层 layout 可以在渲染自身时读取页面声明的标题:

struct Title(&'static str);

#[layout("/", with(Title("My shop")))]
async fn shell(cx: &Cx, slot: Slot<'_>) -> Result<impl View> {
    let Title(title) = context::<Title>(cx);
    Ok(view! {
        <!DOCTYPE html>
        <html><head><title>(title)</title></head><body>(slot)</body></html>
    })
}

RouterBuilder::build 中先收集每个 layout 的 context,再为每个 page 计算匹配的 layout 链,按“外层先、内层后、页面最后”的顺序安装(builder.rs)。PageWithLayouts::context 与 context.md 都说明了整体优先级:

  1. 路由器构建器上的 with(...)(全局值);
  2. 包装该路由的 layer(外层 → 内层);
  3. layout(外层 → 内层);
  4. 页面自身的 with(...);
  5. 请求期间通过 cx.with(...) 追加的值。

#[page] 也可以在函数体里读取自己的上下文:

#[page("/titled", with(Title("titled")))]
async fn titled(cx: &Cx) -> Result<impl View> {
    let title = context::<Title>(cx).0;
    Ok(view! { <p>(title)</p> })
}

布局按前缀匹配,遵循整段前缀语义:/admin 不会匹配 /administrator(page.rs 与 builder.rs 的测试)。多个前缀 layout 会从“最少具体”到“最具体”嵌套:/ → /settings → 页面。

七、页面即组件:在 view! 中内联渲染

这是 #[page] 相对 #[route] 最独特的能力。宏会把原函数再生成一份标注了 #[component] 的版本,并额外生成一个同名常量作为“页面标记”:

#[component]
#face

#[doc(hidden)]
#[allow(non_upper_case_globals)]
#vis const #ident: #ident = #ident { __marker: PhantomData };

见 page.rs。同名常量让函数名在表达式位置也能当作值使用,从而支持 Router::builder().page(home)、&home as &dyn HrefTarget 等用法。

当页面带请求体参数时,宏会把第二个参数改名为 body,并在函数体开头用原来的模式重新绑定:

// 原始写法
async fn contact(cx: &Cx, Form(input): Form<Search>) -> Result<impl View>

// 组件形态(等价)
async fn contact(cx: &Cx, body: Form<Search>) -> Result<impl View> {
    let Form(input) = body;
    // ...
}

因此调用方传入的是已经解析好的值,不会触达真正的请求解析:

#[page]
async fn preview(cx: &Cx) -> Result<impl View> {
    let query = Search { q: String::from("topcoat") };
    Ok(view! {
        contact::contact(body: Form(query))
    })
}

测试 renders_pages_as_components 断言 /composed 的响应为 <h1>home</h1><p>searching for topcoat</p><p>/composed</p>,其中第一段来自 home(),第二段来自 search(body: Form(query)),第三段来自 whoami() 读取的 uri(cx).path()(macro/tests/page.rs)。这说明页面作为组件时会共享同一个请求上下文,uri(cx) 仍是 /composed。

由此可以设计出“页面复用”模式:把可复用的 UI 片段写成 #[page],既能独立访问某个 URL,也能被更高层页面组合进来,无需拆成两个函数。

八、链接、当前页判定与宏生成的其它资源

虽然 page.md 没有展开链接,但宏实际还生成了 impl HrefTarget:

impl HrefTarget for #ident {
    fn path<'cx>(&self, cx: &'cx Cx) -> &'cx Path {
        match route_endpoint(cx, *ID) {
            Some(endpoint) => endpoint.path(),
            None => panic!("page `...` is not registered on the router serving this request"),
        }
    }
}

见 page.rs。这意味着:

#[page("/self-linked")]
async fn self_linked(cx: &Cx) -> Result<impl View> {
    Ok(view! { <a href=(href!(self_linked))>"self-linked"</a> })
}

可以正常生成 href="/self-linked",测试也验证了这一点(macro/tests/page.rs)。href! 会在运行时通过当前请求匹配到的路由反查真实路径,所以模块改名、移动文件后链接自动跟随。更多用法(路径参数、查询串、fragment、is_current)见 href.md。

另外,宏为每个页面生成一个 LazyLock<RouteId> 作为稳定身份(page.rs),Page::is_current 就是靠它比较当前路由(src/page.rs)。注意其文档警告:若请求没有匹配任何路由(404 或 405),调用 is_current 会 panic,因此在导航组件中使用时要确认处于已匹配的页面上下文中。

开启 discover feature 后,宏还会提交一行 inventory::submit!,把页面注册进链接期收集表;这正是 discover 系列方法能“零手写注册”的原因。

九、冲突、404 与 405:构建期就会失败的情况

RouterBuilder::build 会对路由表做一致性检查(builder.rs):

  • 同一路径 + 同一方法注册两次 → duplicate route registered for GET /x``;
  • 同一路径注册两个 * 路由 → duplicate any-method route registered for /x``;
  • 方法集合部分重叠(如一个 [GET, POST] 与一个 POST)也算冲突;
  • 声明了空方法集合 → route /x registers no methods。

模块路由还有一个额外约束:同一模块内的两个 #[page] 会得到相同路径,它们可以各自服务不同方法,但方法重叠时会在 build 阶段 panic(module.md 的“Conflicts”一节)。同理,同一逻辑路径下的两个模块派生 layout 或 layer 也会被拒绝,因为链期发现不定义顺序;需要叠加顺序时改用 RouterBuilder::layer 显式注册。

排查时的经验法则:

现象 可能原因 排查方向
405 路径命中,方法未声明 检查是否写了 #[page(POST)] / [GET, POST] / *
404 模块未被编译、路径推导不符 检查父模块是否有 mod xxx;,是否遗漏 ./ 前缀,是否落在 _group 分组中
build 时 panic 重复路径/方法、空方法集 查看 panic 信息中的方法名与路径
href! panic 页面未注册到当前路由器 绝对路径页面是否忘了 .page(...) 或 .discover()

十、把散点串起来:一份可运行的模块路由示例

下面示例综合了本文涉及的多数要点,目录结构要求 Rust 通过 mod 声明编译到每个模块(模块路由不扫描文件系统):

src/
  app.rs            # module_router!(),根页面 /
  app/
    about.rs        # /about
    signup.rs       # /signup(GET)与 /signup(POST)
    settings.rs     # /settings 与 /settings/export
// src/app.rs
use topcoat::{context::Cx, router::module_router, router::Slot, router::layout, Result, view::{View, view}};
use topcoat::router::Router;

mod about;
mod settings;
mod signup;

struct Title(&'static str);

pub fn router() -> Router {
    module_router!().build()
}

#[layout]
async fn root_layout(cx: &Cx, slot: Slot<'_>) -> Result<impl View> {
    let title = topcoat::context::try_context::<Title>(cx).map(|t| t.0).unwrap_or("Topcoat");
    Ok(view! {
        <!DOCTYPE html>
        <html>
            <head><title>(title)</title></head>
            <body>
                <nav>
                    <a href=(topcoat::router::href!(page))>"home"</a>
                    <a href=(topcoat::router::href!(about::about))>"about"</a>
                </nav>
                (slot)
            </body>
        </html>
    })
}

#[page]
async fn page(cx: &Cx) -> Result<impl View> {
    Ok(view! { <h1>"home"</h1> })
}
// src/app/about.rs
use topcoat::{context::Cx, router::page, view::{View, view}, Result};

#[page(with(Title("About")))]
pub async fn about(cx: &Cx) -> Result<impl View> {
    Ok(view! { <h1>"About"</h1> })
}
// src/app/signup.rs
use serde::Deserialize;
use topcoat::{context::Cx, router::{content::Form, page}, view::{View, view}, Result};

#[derive(Deserialize)]
pub struct Signup { email: String }

#[page]
pub async fn page(cx: &Cx) -> Result<impl View> {
    Ok(view! {
        <form method="post" action=(topcoat::router::href!(submit))>
            <input type="email" name="email">
            <button type="submit">"Sign up"</button>
        </form>
    })
}

#[page(POST, with(Title("Thanks")))]
pub async fn submit(cx: &Cx, Form(input): Form<Signup>) -> Result<impl View> {
    Ok(view! { <h1>"Welcome, " (input.email)</h1> })
}
// src/app/settings.rs
use topcoat::{context::Cx, router::page, view::{View, view}, Result};

#[page(with(Title("Settings")))]
pub async fn settings(cx: &Cx) -> Result<impl View> {
    Ok(view! { <h1>"Settings"</h1> })
}

#[page("./export")]
pub async fn export(cx: &Cx) -> Result<impl View> {
    Ok(view! { <h1>"Export"</h1> })
}

要点回顾:

  • module_router!() 必须写在 app 模块根部,并声明所有子模块;
  • 同一模块里 page 与 submit 共享 /signup 路径,靠方法区分(GET / POST),不会冲突;
  • submit 的 with(Title("Thanks")) 在 POST /signup 时覆盖根 layout 的默认标题,但由于页面本身不渲染 layout 的 <title>,实际效果取决于哪个 layout 读取 Title——这正是 with(...) 在构建期初始化的价值:layout 可以比页面更早拿到它;
  • ./export 让一个函数挂在模块路径下,无需新建 settings/export.rs 模块。

可以参考仓库中更完整的模块路由样例 examples/module-router/src/app.rs 与真实应用 demos/admin(其中 #[page(with(Section::Dashboard))]、#[page(with(Crumb::new(...)))] 展示了路由上下文用于导航与面包屑的实践)。

十一、常见问题速查

为什么 #[page] 的 cx 参数用不到也必须写? 因为宏生成的是统一的视图组件与渲染函数签名,Cx 承载请求上下文,Topcoat 在调用时自动注入(见 context.md)。

#[page] 能否返回 JSON? 不建议。页面语义绑定 View;返回 JSON 请用 #<a href="https://link.gitcode.com/i/1a1bb19937aa523f95d6a3145c4b2115" target="_blank">route] 与 AsyncIntoResponse 类型,参考 [route.md。

显式路径页面为什么 404? module_router!() 只收集模块派生页面。绝对路径页面需要 .page(fn) 或 .discover() 注册;.discover() 还能一并收集显式路径的 route、layout、layer。

with(...) 的值能随请求变化吗? 不能,它在构建路由器时初始化一次。需要请求相关值时,可以存放一个函数(如示例工程中的 Crumb::new(async |cx| ...)),在渲染时用 cx 调用;调用本身不做 memoize,需要缓存时配合 #[memoize]。

两个页面能共用同一 URL 吗? 只有在方法集合不重叠时才可以;否则 build 阶段会 panic。* 与具体方法可以共存,具体方法优先。

页面作为组件时为什么请求体参数变成了 body? 宏会把第二个参数改名为 body 并在函数体开头用原模式重新绑定,从而让调用方直接传入已解析的值(page.rs)。

十二、结语

#[page] 把“URL 从哪来”“响应什么方法”“请求体怎么解析”“元数据何时可用”“能否被复用”这五个问题压缩进一个属性宏里:路径决定注册模型(ModulePage 还是 Page),方法声明决定分发行为,签名约束保证视图渲染链路稳定,with(...) 让 layout 先于页面读到元数据,而组件化展开则让页面可以被自由组合。理解这层宏展开与 RouterBuilder 的构建顺序,比记住语法更能帮助你在真实项目中定位 404、405 与 build 期 panic。

登录后查看全文
topcoat