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

样式与约定封装

命名约定

类型命名示例
Request{Action}{Entity}RequestCreateUserRequest
Handler{Action}{Entity}HandlerCreateUserHandler
Response DTO{Entity}Dto / {Entity}ViewUserDto, UserView
Service{Entity}ServiceDocService
Entity{Entity}EntityUserEntity
Event{Entity}{Action}EventUserCreatedEvent

API 路径约定

/api/{resource}           # 集合
/api/{resource}/{id}      # 单个资源
/api/{resource}/{id}/{sub} # 子资源
/api/auth/{action}        # 认证相关

错误消息风格

#![allow(unused)]
fn main() {
// ✅ 面向用户
Error::not_found(format!("User '{}' not found", id))
Error::validation("Email is required")

// ❌ 暴露内部
Error::internal(format!("SQL error: {}", db_err))
}

DTO 设计

#![allow(unused)]
fn main() {
// 请求 DTO:只包含输入字段;只需派生 WebxRequestMeta
#[derive(WebxRequestMeta)]
pub struct CreateUserRequest {
    pub name: String,
    pub email: String,
    // 不包含 id、created_at 等系统字段
}

// 需要登录的请求:身份作为字段,而不是在 Handler 里解析 claims
#[derive(WebxRequestMeta)]
pub struct UpdateProfileRequest {
    #[fromclaim]
    pub user: IdentityUser,
    pub display_name: String,
}

// 响应 DTO:包含输出字段
#[derive(Serialize)]
pub struct UserDto {
    pub id: String,
    pub name: String,
    pub email: String,
    pub created_at: String,
}
}

版本化

版本号写进路径,由路由宏逐条声明(没有 #[controller] 这类控制器宏):

#![allow(unused)]
fn main() {
#[get("/api/v1/users")]
impl IRequest<Vec<UserDto>> for ListUsersV1Request {}

#[get("/api/v2/users")]
impl IRequest<Vec<UserDto>> for ListUsersV2Request {}
}

项目级封装

在团队中创建 style-guide.md 和 CLAUDE.md / .cursor/rules,统一 AI 生成代码的风格。

小结

一致的命名和约定降低认知负担,使团队代码像一个人写的。

下一节:第三方库集成