HTTP 路由

日常 JSON 业务接口优先用 #[query] 与 #[mutation],需要自定义状态码、响应头、路径或重定向等底层 HTTP 控制时使用本篇的 App::routes。本篇实现配置读取与文本回显两个接口并编写自动化测试。

编写路由与配置#

工程环境准备见 第一个应用,业务契约写法见 Procedure。

第 1 步,新建 Cargo.toml:

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 两个处理函数:

Rust
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:

Rust
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,另开终端依次请求配置接口、合法短文本与超长文本(阅读约定):

Shell
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}
400
  • GET /config 返回默认运行环境 local 与 max_text_bytes 的默认值 256。
  • POST /echo 传入 7 字节文本时返回 200 与字节统计;传入 300 字节文本时触发 AppErr::bad_request,返回状态码 400。

自动化测试#

开启 testing 特性后,kxed::testing::TestApp 会在本地回环临时端口上启动真实应用并发送请求断言。

在 Cargo.toml 末尾追加:

TOML
[dev-dependencies]
kxed = { version = "0.0.5-alpha", features = ["testing"] }

新建 src/tests.rs:

Rust
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 的完整内容是:

Rust
#[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 即可执行上述测试。

架构图示

常见排错#

现象原因解决方法
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")

参考#