路由与响应进阶
本篇在一个服务里组合命名路由、REST 资源路由、接口弃用响应头、自动 ETag 缓存协商与响应后异步收尾。适合需要统一管理路径前缀、平滑下线旧版本或减少重复响应传输的场景。
编写路由与响应示例#
第 1 步,新建 Cargo.toml:
[package]
name = "guide-http-advanced"
version = "0.0.5-alpha"
edition = "2024"
rust-version = "1.98.1"
[dependencies]
kxed = "0.0.5-alpha"第 2 步,新建 src/handlers.rs,实现按名反查路由、文章资源接口、带自动 ETag 的价格接口与响应后异步记账:
use kxed::http::Etagged;
use kxed::prelude::*;
use std::sync::atomic::{AtomicU64, Ordering};
#[derive(Default)]
pub(crate) struct Receipts(AtomicU64);
#[derive(Serialize)]
pub(crate) struct Price {
sku: String,
cents: u64,
}
pub(crate) async fn home(ctx: AppCtx) -> Result<String, AppErr> {
Ok(format!("see {}\n", ctx.route_url("posts.index", &[])?))
}
pub(crate) async fn index(ctx: AppCtx) -> Result<String, AppErr> {
let first = ctx.route_url("posts.show", &[("id", "first post")])?;
Ok(format!("posts, first at {first}\n"))
}
pub(crate) async fn store() -> (StatusCode, &'static str) {
(StatusCode::CREATED, "created\n")
}
pub(crate) async fn show(Path(id): Path<String>) -> String {
format!("post {id}\n")
}
pub(crate) async fn update(Path(id): Path<String>) -> String {
format!("updated {id}\n")
}
pub(crate) async fn price(Path(sku): Path<String>) -> Etagged<Price> {
Etagged(Price { sku, cents: 1999 })
}
pub(crate) async fn order(ctx: AppCtx) -> Result<&'static str, AppErr> {
ctx.after_response(|ctx| async move {
ctx.require_state::<Receipts>()?.0.fetch_add(1, Ordering::Relaxed);
Ok(())
})?;
Ok("accepted\n")
}
pub(crate) async fn receipts(ctx: AppCtx) -> Result<String, AppErr> {
let sent = ctx.require_state::<Receipts>()?.0.load(Ordering::Relaxed);
Ok(format!("receipts sent: {sent}\n"))
}第 3 步,挂载命名首页、posts 资源路由、/v1 弃用分组、价格缓存接口与下单回执路由,写 src/main.rs:
mod handlers;
use kxed::http::ResourceRoutes;
use kxed::prelude::*;
use std::time::{Duration, SystemTime};
#[kxed::main]
async fn main() -> kxed::Result<()> {
App::new()
.provide(handlers::Receipts::default())
.routes(|router| {
router
.route("/", get(handlers::home).name("home"))
.resource(
"posts",
ResourceRoutes::new()
.index(handlers::index)
.store(handlers::store)
.show(handlers::show)
.update(handlers::update),
)
.group("/v1", |v1| {
v1.deprecated(SystemTime::UNIX_EPOCH + Duration::from_secs(1_767_225_600))
.sunset(SystemTime::UNIX_EPOCH + Duration::from_secs(1_798_761_600))
.route("/posts", get(handlers::index));
})
.route("/prices/{sku}", get(handlers::price))
.route("/orders", post(handlers::order))
.route("/receipts", get(handlers::receipts));
})
.run()
.await
}验证#
在工程目录运行 cargo run,另开终端验证命名路由、资源路由、弃用响应头、ETag 304 协商与响应后异步动作(阅读约定):
curl --fail http://127.0.0.1:8080/
curl --fail http://127.0.0.1:8080/posts
curl --fail http://127.0.0.1:8080/posts/first%20post
curl --fail -X PATCH http://127.0.0.1:8080/posts/7
curl --silent --output /dev/null --write-out '%{http_code}\n' -X POST http://127.0.0.1:8080/posts
curl --silent --output /dev/null --write-out '%{http_code}\n' -X DELETE http://127.0.0.1:8080/posts/7
curl --silent --include http://127.0.0.1:8080/v1/posts | tr -d '\r' | grep -i -E '^(deprecation|sunset):'
url=http://127.0.0.1:8080/prices/tea
tag=$(curl --silent --include "$url" | tr -d '\r' | sed -n 's/^[Ee][Tt]ag: //p')
echo "$tag" | cut -c1-3
curl --silent --output /dev/null --write-out '%{http_code}\n' --header "If-None-Match: $tag" "$url"
curl --silent --output /dev/null --write-out '%{http_code}\n' --head --header "If-None-Match: $tag" "$url"
curl --silent --output /dev/null --write-out '%{http_code}\n' --header 'If-None-Match: W/"stale"' "$url"
curl --fail --silent -X POST http://127.0.0.1:8080/orders
curl --fail --silent http://127.0.0.1:8080/receipts预期输出:
see /posts
posts, first at /posts/first%20post
post first post
updated 7
201
405
deprecation: @1767225600
sunset: Fri, 01 Jan 2027 00:00:00 GMT
W/"
304
304
200
accepted
receipts sent: 1- 前 8 行依次验证了
route_url反向拼址与空格自动编码%20、资源动作POST返回201、未注册的DELETE返回405,以及/v1/posts附带标准deprecation与sunset头。 - 后 6 行验证了
Etagged生成弱摘要W/"..."、GET/HEAD携带一致If-None-Match返回304、过期值重返200,以及POST /orders响应发出后异步把回执计数加到1。
命名路由、资源路由与弃用头#
router.resource("posts", ResourceRoutes::new()..) 按以下约定展开标准 REST 路径与全局唯一路由名:
| 动作方法 | HTTP 方法与路径 | 自动注册的路由名 |
|---|---|---|
index / store | GET /posts、POST /posts | posts.index、posts.store |
create / edit | GET /posts/create、GET /posts/{id}/edit | posts.create、posts.edit |
show / update / destroy | GET、PUT/PATCH、DELETE /posts/{id} | posts.show、posts.update、posts.destroy |
- 反查与参数编码:
ctx.route_url(name, &[("key", "value")])?按单段路径做 percent-encode 并拒绝含/、.、..的普通参数(多段路径改用{*rest});运行./app routes可核对全部路由名,生成限时链接见 签名 URL 与 webhook。 - 弃用头预检与覆盖:
deprecated(since)输出 RFC 9745Deprecation: @<unix 秒>,sunset(at)输出 RFC 8594Sunset: <HTTP-date>,作用于组内全部正常响应与 405 响应;若sunset早于deprecated或组内含 WebSocket 路由,启动预检会直接拦住。 - 同会话并发串行:需要防止同一浏览器连点覆盖 Session 时,开启
session特性并在路由上挂载session_block(lease, wait),超时返回 429session_busy(见 Session 会话锁)。
ETag 缓存协商与响应后执行#
把返回值从 Json<T> 换成 Etagged<T> 后,框架按 JSON 字节计算 blake3 弱 ETag(多实例下与是否压缩无关、结果一致),并对 GET/HEAD 的 If-None-Match 自动改写为无体 304(保留 ETag、Vary、Cache-Control 与 Set-Cookie)。如需省去查库,可在 handler 内自行比对版本列并返回 StatusCode::NOT_MODIFIED。
ctx.after_response(|ctx| async move { .. })? 把轻量收尾移到响应写完之后运行,与后台持久任务的分工如下:
| 对比维度 | ctx.after_response(..) | ctx.submit(task)(后台任务) |
|---|---|---|
| 运行位置 | 当前 HTTP 实例内存顺序执行 | 持久化入库,由工作池调度执行 |
| 崩溃与重试 | 实例崩溃即丢失,失败记 warn 不重试 | 重启不丢,支持退避重试与死信队列 |
| 适用场景 | 刷新本地缓存、轻量指标统计 | 扣款对账、交易邮件、出站 webhook |
- 执行边界:主 handler 返回 5xx、超时或 panic 时自动跳过后置闭包;单请求最多登记 16 个闭包(超限返 500
http_after_response_exceeded),非 HTTP 上下文调用返 500http_after_response_unsupported;开启数据库读写分离时后置闭包的新ctx不继承主库 sticky 标记,读刚写数据请调ctx.db()?。
常见排错#
| 现象 | 原因 | 解决方法 |
|---|---|---|
| 启动提示路由名重复 | 在 /v1 与 /v2 两个分组里都调了 .resource("posts", ..) 导致 posts.* 冲突 | 旧版本分组改用 .route(..) 指定带前缀的独立路由名(如 "v1.posts.index") |
调 ctx.route_url 返回 500 http_route_not_found | 路由名拼错、缺少占位符参数,或单段参数含 / 与 .. | 运行 cargo run -- routes 核对 name 列,多段参数改用 {*rest} |
带上 If-None-Match 仍返回 200 | 请求不是 GET/HEAD,或手写了 ETag 头而非返回 Etagged<T> | 读取接口统一返回 Etagged<T> 交由框架自动协商 304 |
after_response 内查不到刚写入的数据 | 开启了读写分离,后置闭包新 ctx 未继承主库 sticky 标记 | 在后置闭包内显式使用主库 ctx.db()? 而非 ctx.read_db()? |
参考#
- SPEC 第 1.1 节:命名路由、资源路由、弃用响应头、动态 ETag 与响应后执行规格
- HTTP 路由:
Router、MethodRoute、提取器与TestApp集成测试 - Session 会话锁:
session_block租约与错误码说明