HTTP 路由
日常 JSON 业务接口优先用 #[query] 与 #[mutation],需要自定义状态码、响应头、路径或重定向等底层 HTTP 控制时使用本篇的 App::routes。本篇实现配置读取与文本回显两个接口并编写自动化测试。
编写路由与配置#
工程环境准备见 第一个应用,业务契约写法见 Procedure。
第 1 步,新建 Cargo.toml:
[package]
name = "guide-http"
version = "0.0.5-alpha"
edition = "2024"
rust-version = "1.98.1"
[dependencies]
kxed = "0.0.5-alpha"第 2 步,新建 src/web.rs,声明带范围预检的 ChatConfig 配置段,以及读取配置的 show_config 和校验文本长度的 echo 两个处理函数:
use kxed::prelude::*;
#[derive(Deserialize, ConfigSection)]
#[config(check = check_chat)]
pub(crate) struct ChatConfig {
#[config(default = 256)]
pub(crate) max_text_bytes: usize,
}
fn check_chat(config: &ChatConfig) -> Result<(), String> {
if (1..=4096).contains(&config.max_text_bytes) {
Ok(())
} else {
Err("max_text_bytes must be in 1..=4096".into())
}
}
#[derive(Serialize)]
pub(crate) struct ConfigView {
environment: String,
max_text_bytes: usize,
}
pub(crate) async fn show_config(ctx: AppCtx) -> Result<Json<ConfigView>, AppErr> {
let chat = ctx.config::<ChatConfig>()?;
Ok(Json(ConfigView {
environment: ctx.environment()?,
max_text_bytes: chat.max_text_bytes,
}))
}
#[derive(Deserialize)]
pub(crate) struct EchoRequest {
text: String,
}
#[derive(Serialize)]
pub(crate) struct EchoResponse {
text: String,
bytes: usize,
}
pub(crate) async fn echo(
ctx: AppCtx,
Json(request): Json<EchoRequest>,
) -> Result<Json<EchoResponse>, AppErr> {
let chat = ctx.config::<ChatConfig>()?;
if request.text.len() > chat.max_text_bytes {
return Err(AppErr::bad_request(format!(
"text exceeds {} bytes",
chat.max_text_bytes
)));
}
Ok(Json(EchoResponse {
bytes: request.text.len(),
text: request.text,
}))
}第 3 步,通过 App::routes 将两个函数挂载到 /config 与 /echo,写 src/main.rs:
mod web;
use kxed::prelude::*;
#[kxed::main]
async fn main() -> kxed::Result<()> {
App::new()
.routes(|router| {
router
.route("/config", get(web::show_config))
.route("/echo", post(web::echo));
})
.run()
.await
}请求提取与类型化配置#
原生 HTTP handler 是标准异步函数,返回值支持任意实现 IntoResponse 的类型,业务错误统一返回 AppErr(自动输出对应 HTTP 状态码与带 error 字段的 JSON,完整构造器见 HTTP 参考)。常用参数提取器如下:
| 参数类型 | 用途 | 参数位置要求 |
|---|---|---|
AppCtx | 读取全局共享状态、类型化配置、当前环境与数据库连接 | 任意位置 |
Path<T> / Query<T> | 解析 URL 路径参数或查询字符串,失败返回 400 JSON | 消费请求体的参数之前 |
ClientIp / RequestScheme / PeerAddr | 提取真实客户端 IP、请求协议或直连对端地址(见 客户端 IP) | 消费请求体的参数之前 |
Json<T> / Form<T> | 读取并反序列化请求体,格式不合法返回 400 JSON | 必须放在参数列表最后 |
#[derive(ConfigSection)] 让结构体在应用启动前自动从配置文件和环境变量加载并完成校验(取值优先级见 配置):
- 配置段命名空间:默认去掉类型名末尾的
Config并转为 snake_case(ChatConfig对应config/chat.toml或[chat]),可用#[config(namespace = "..")]修改。 - 默认值与必填检查:标了
#[config(default = ..)]的字段自带默认值;未标默认值的字段缺失时,进程在启动前直接报错并指出配置键名与对应环境变量。 - 自定义范围预检:
#[config(check = ..)]指定的校验函数在./app config check与进程启动时都会执行,不满足条件时拒绝启动。
验证#
在工程目录运行 cargo run,另开终端依次请求配置接口、合法短文本与超长文本(阅读约定):
curl --fail http://127.0.0.1:8080/config; echo
curl --fail -H 'content-type: application/json' -d '{"text":"one two"}' http://127.0.0.1:8080/echo; echo
TEXT=$(head -c 300 /dev/zero | tr '\0' x)
curl --silent --output /dev/null --write-out '%{http_code}\n' \
-H 'content-type: application/json' -d "{\"text\":\"$TEXT\"}" http://127.0.0.1:8080/echo预期输出:
{"environment":"local","max_text_bytes":256}
{"text":"one two","bytes":7}
400GET /config返回默认运行环境local与max_text_bytes的默认值256。POST /echo传入 7 字节文本时返回200与字节统计;传入 300 字节文本时触发AppErr::bad_request,返回状态码400。
自动化测试#
开启 testing 特性后,kxed::testing::TestApp 会在本地回环临时端口上启动真实应用并发送请求断言。
在 Cargo.toml 末尾追加:
[dev-dependencies]
kxed = { version = "0.0.5-alpha", features = ["testing"] }新建 src/tests.rs:
use crate::web;
use kxed::prelude::*;
#[kxed::tokio::test]
async fn echo_counts_bytes() {
let app = App::new().routes(|router| {
router.route("/echo", post(web::echo));
});
let running = kxed::testing::TestApp::start(app).await.unwrap();
running
.post_json("/echo", &kxed::serde_json::json!({ "text": "one two" }))
.await
.assert_status(200)
.assert_json_path("/bytes", 7);
running.shutdown().await.unwrap();
}挂上测试模块后,到这一步 src/main.rs 的完整内容是:
#[cfg(test)]
mod tests;
mod web;
use kxed::prelude::*;
#[kxed::main]
async fn main() -> kxed::Result<()> {
App::new()
.routes(|router| {
router
.route("/config", get(web::show_config))
.route("/echo", post(web::echo));
})
.run()
.await
}运行 cargo test 即可执行上述测试。
flowchart LR
start["TestApp::start(app)<br/>回环临时端口启动"] --> req["post_json / acting_as / call / ws"]
req --> assert["assert_status · assert_json_path<br/>drain_tasks · assert_submitted"]
assert --> stop["shutdown().await 优雅停机"]常见排错#
| 现象 | 原因 | 解决方法 |
|---|---|---|
| handler 编译提示提取器 trait 未满足 | Json<T> 或 Form<T> 消费了请求体,但被放在了 Path<T> 或 AppCtx 前面 | 将消费请求体的 Json<T> / Form<T> 移到参数列表最后一位 |
编译提示 takes a kxed MethodRoute | 误导入了 axum::routing::get 而非框架路由构造方法 | 删掉 axum::routing 导入,统一使用 kxed::prelude::* 中的 get、post |
启动提示路径必须以 / 开头 | router.route("echo", ..) 漏写了前导斜杠 | 路由路径与分组根路径一律以 / 开头(如 "/echo") |
参考#
- HTTP 参考:路由挂载、分组中间件、
AppErr构造器与TestApp方法表 - SPEC 第 5.1 节:HTTP 协议合同与上下文能力清单
- 分页、OpenAPI 与外部 HTTP:列表分页
PageQuery、OpenAPI 文档与出站 HTTP 客户端 - examples/http-features:请求体字段校验与多语言错误文案示例