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 项目

cargo new my-api
cd my-api

配置 Cargo.toml

[package]
name = "my-api"
version = "0.1.0"
edition = "2021"

[dependencies]
rust-webx = "2.9"
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
async-trait = "0.1"

包名 vs 导入名:Cargo.toml 里写包名 rust-webx,代码里 use webx::*;。 各子 crate 的完整对照表见 Crate 分层结构。

当前发布 2.9.4;"2.9" 是 semver 范围(框架家族内部锁步,不需要精确钉到补丁号), 补丁升级与迁移摘要见第十六章 迁移指南,N-2 源码兼容基线为 2.9.1。

若在本仓库内开发,使用 path 依赖:

rust-webx = { path = "../crates/webx" }

可选:appsettings.json

在项目根目录创建配置文件(框架自动加载):

{
  "App": {
    "Name": "My API",
    "Urls": ["http://0.0.0.0:5000"]
  },
  "Jwt": {
    "Secret": "change-me-in-production"
  },
  "Cors": {
    "Origins": ["http://localhost:5173"],
    "Methods": ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
    "Headers": ["Content-Type", "Authorization"]
  }
}

CORS 默认关闭(Origins 为空 = 不发送 CORS 头);需要跨域时显式列出前端 origin。Production 拒绝 "*",开发环境可额外提供 appsettings.Development.json,框架在 AppMode::Development 下自动合并。

项目目录建议

即使是 Hello World,也建议从一开始就采用约定结构:

my-api/
├── Cargo.toml
├── appsettings.json
└── src/
    ├── main.rs
    ├── contracts/     # 请求定义(路由 + DTO)
    │   └── mod.rs
    └── handlers/      # 处理器实现
        └── mod.rs

在 main.rs 中声明模块:

#![allow(unused)]
fn main() {
mod contracts;
mod handlers;
}

从 Workspace 模板创建

也可直接参考本仓库的 docbit 项目(examples/docbit/,独立 workspace):

cargo run --manifest-path examples/docbit/Cargo.toml -p docbit-host

Docbit 展示了完整的中型项目结构,详见 第十五章案例研究。

小结

依赖只需 rust-webx 一个伞 Crate 即可获得全部框架能力。下一节编写第一个端点。

下一节:Hello World 详解