第一个 CRUD API
本节实现一个内存中的用户 CRUD,展示 GET/POST/PUT/DELETE 四种路由模式。
数据模型
src/contracts/user.rs:
#![allow(unused)]
fn main() {
use webx::*;
use serde::Serialize;
#[derive(Clone, Serialize)]
pub struct UserDto {
pub id: String,
pub name: String,
pub email: String,
}
// ── List ──
#[derive(WebxRequestMeta)]
pub struct ListUsersRequest;
#[get("/api/users")]
impl IRequest<Vec<UserDto>> for ListUsersRequest {}
// ── Get by ID ──
#[derive(WebxRequestMeta)]
pub struct GetUserRequest {
#[frompath]
pub id: String,
}
#[get("/api/users/{id}")]
impl IRequest<UserDto> for GetUserRequest {}
// ── Create ──
#[derive(WebxRequestMeta)]
pub struct CreateUserRequest {
pub name: String,
pub email: String,
}
#[post("/api/users")]
impl IRequest<UserDto> for CreateUserRequest {}
// ── Update ──
#[derive(WebxRequestMeta)]
pub struct UpdateUserRequest {
#[frompath]
pub id: String,
pub name: String,
pub email: String,
}
#[put("/api/users/{id}")]
impl IRequest<UserDto> for UpdateUserRequest {}
// ── Delete ──
#[derive(WebxRequestMeta)]
pub struct DeleteUserRequest {
#[frompath]
pub id: String,
}
#[delete("/api/users/{id}")]
impl IRequest<()> for DeleteUserRequest {}
}
共享存储
src/handlers/user.rs:
#![allow(unused)]
fn main() {
use std::collections::HashMap;
use std::sync::Arc;
use webx::*;
use tokio::sync::RwLock;
use crate::contracts::user::*;
// ── 共享存储:注册为单例,由 DI 注入 ──
#[derive(Default)]
pub struct UserStore {
users: RwLock<HashMap<String, UserDto>>,
}
impl UserStore {
pub async fn insert(&self, id: String, user: UserDto) {
self.users.write().await.insert(id, user);
}
pub async fn get(&self, id: &str) -> Option<UserDto> {
self.users.read().await.get(id).cloned()
}
}
// ── List ──
#[derive(Default)]
struct ListUsersHandler;
#[handler]
#[async_trait]
impl IRequestHandler<ListUsersRequest, Vec<UserDto>> for ListUsersHandler {
async fn handle(&mut self, _req: ListUsersRequest) -> ActionResult<Vec<UserDto>> {
// 实际项目中通过 DI 注入 store
Ok(vec![])
}
}
}
带依赖注入的完整版本,用 #[derive(Inject)] 声明 Handler 依赖,并用 #[handler(inject)] 标记注入式构造:
#![allow(unused)]
fn main() {
#[derive(Inject)]
struct CreateUserHandler {
#[inject]
store: Arc<UserStore>,
}
#[handler(inject)]
#[async_trait]
impl IRequestHandler<CreateUserRequest, UserDto> for CreateUserHandler {
async fn handle(&mut self, req: CreateUserRequest) -> ActionResult<UserDto> {
let id = uuid::Uuid::new_v4().to_string();
let user = UserDto {
id: id.clone(),
name: req.name,
email: req.email,
};
self.store.insert(id, user.clone()).await;
Ok(user)
}
}
}
注册共享依赖
Handler 由 #[handler] / #[handler(inject)] 自动向 inventory 注册,HTTP 分发通过 HandlerCache 查找,不经过 DI 查找 dyn IRequestHandler。main.rs 只需注册 Handler 依赖的服务:
#[webx::main]
async fn main() {
Host::builder()
.register(|svc| {
svc.singleton::<UserStore>(|_| Arc::new(UserStore::default()));
})
.build()
.run()
.await
.expect("Server failed");
}
测试 API
# 创建用户
curl -X POST http://localhost:5000/api/users \
-H "Content-Type: application/json" \
-d '{"name":"Alice","email":"alice@example.com"}'
# 获取列表
curl http://localhost:5000/api/users
# 获取单个
curl http://localhost:5000/api/users/{id}
# 更新
curl -X PUT http://localhost:5000/api/users/{id} \
-H "Content-Type: application/json" \
-d '{"name":"Alice Updated","email":"alice@example.com"}'
# 删除
curl -X DELETE http://localhost:5000/api/users/{id}
错误处理示例
#![allow(unused)]
fn main() {
async fn handle(&mut self, req: GetUserRequest) -> ActionResult<UserDto> {
self.store
.get(&req.id)
.await
.ok_or_else(|| Error::not_found(format!("User {} not found", req.id)))
}
}
Error::not_found 自动映射为 HTTP 404,响应体为 RFC 9457 application/problem+json(type / title / status / detail)。
需要登录的接口:身份直接进 Request
用户 CRUD 本身是公开的。给「修改个人资料」加一条需要登录的端点时,不需要在 Handler 里解析 token:
#![allow(unused)]
fn main() {
#[derive(WebxRequestMeta)]
pub struct UpdateProfileRequest {
#[fromclaim]
pub user: IdentityUser, // 未登录 → 401
pub display_name: String, // JSON body
}
#[put("/api/profile")]
#[authorize]
impl IRequest<UserDto> for UpdateProfileRequest {}
}
#![allow(unused)]
fn main() {
async fn handle(&mut self, req: UpdateProfileRequest) -> ActionResult<UserDto> {
let user = req.require_user()?;
self.store
.update_profile(&user.id, &user.tenant_id, req.display_name)
.await
}
}
如果端点允许游客访问(例如商品详情要显示「是否已收藏」),把字段写成 #[fromclaim(optional)] viewer: Option<IdentityUser>(匿名必须显式声明),
未登录时就是 None,不会 401。完整场景见用户身份与多租户。
设计要点
| 实践 | 说明 |
|---|---|
| Request 放 contracts | 路由元数据与 DTO 定义集中,便于查阅 API 契约 |
| Handler 放 handlers | 纯业务逻辑,通过 DI 获取依赖 |
| 请求类型派生 | 每个 Request 都必须派生 WebxRequestMeta(绑定 + OpenAPI 元数据) |
| 路径参数 | 用 #[frompath] 显式声明;GET 的未标记字段先查 query,再回退到路径 |
| Body 字段 | POST/PUT/PATCH 的未标记字段从 JSON body 绑定;Option<T> 表示可选 |
| 身份获取 | 需要登录时用 #[fromclaim] IdentityUser,Handler 只读 req.user |
| 序列化派生 | 请求类型只需 WebxRequestMeta,不必再派生 Deserialize |
小结
CRUD 是检验框架能力的试金石。rust-webx 用统一的四步模式覆盖全部 HTTP 方法,无需为每种方法学习不同 API。
下一节:运行、调试与验证