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

运行、调试与验证

启动服务

基本运行

cargo run

默认监听 appsettings.json 中 App.Urls 配置的地址(默认 http://0.0.0.0:5000)。

指定开发模式

#![allow(unused)]
fn main() {
Host::builder()
    .mode(AppMode::Development)
    .build()
    .run()
    .await?;
}

开发模式会合并 appsettings.Development.json,并启用更详细的日志。

运行本仓库示例

# Docbit 作品集
cargo run --manifest-path examples/docbit/Cargo.toml -p docbit-host

# 仅编译检查
cargo check --workspace

验证端点

curl

curl -v http://localhost:5000/hello
curl -H "Authorization: Bearer <token>" http://localhost:5000/api/auth/me

内置 API 文档

框架在开发模式(AppMode::Development)下自动暴露 API 文档端点:

http://localhost:5000/api/openapi.html   # 内置 API 文档 UI,可浏览所有已注册路由
http://localhost:5000/api/openapi.json   # OpenAPI 3.0 规范

健康检查

GET /health

返回服务健康状态,适用于容器编排探针。

调试技巧

调整 tracing 日志级别

Host::build() 会自动初始化 tracing;用环境变量 RUST_LOG 控制级别(默认 info):

RUST_LOG=debug cargo run

中间件如 RequestTracing、TimingMiddleware 会输出请求耗时与路径。

常见启动错误

错误现象原因解决
No #[handler] registered for request type '...'缺少 #[handler] 的 inventory 注册确认 impl IRequestHandler 上标注了 #[handler] / #[handler(inject)]
route not found 404路由未收集确认 #[get] 标注在 impl IRequest 上
端口占用5000 已被使用修改 App.Urls
类型不匹配Request/Handler 响应类型不一致(编译错误,受 T: IRequest<R> 约束)确保 IRequest<T> 的 T = Handler 的 R;运行期 downcast 失败返回 Error::internal

编译时检查清单

cargo check 2>&1 | head -50   # 查看编译错误
cargo test -p rust-webx-host # 运行框架集成测试

热重载

Rust 暂无内置热重载。开发时推荐使用 cargo-watch:

cargo install cargo-watch
cargo watch -x run

生产构建

cargo build --release
./target/release/my-api

Workspace 的 release profile 已配置 LTO 与 strip,产物体积与性能均经过优化。

小结

运行 rust-webx 应用只需 cargo run;验证通过 curl、内置 API 文档或集成测试。遇到问题时,先查 Handler 注册与路由标注两个最高频原因。

本章完成!下一章进入设计哲学:第三章