04-backend-rust

04-backend-rust is a cursor rule for Cursor from 2154355737/JieShenSheQu. It costs 0 tokens per session (3,267 once invoked), scanned A, original, MIT.

Coding rules for building a Rust web backend with the Actix-Web framework. They describe a layered project structure, recommended libraries, data models, authentication, logging, and related conventions.

In plain words
What is it for?
Use them when creating or reviewing Actix-Web routes, models, repositories, services, middleware, startup code, authentication, or SQLite access.
Why use it?
They give contributors a consistent way to organize backend code and handle common concerns such as databases, JSON, passwords, and tokens.

Cursor rule for Cursor

Written for Cursor: installed under .cursor/.

Good fit Use them when creating or reviewing Actix-Web routes, models, repositories, services, middleware, startup code, authentication, or SQLite access.

Compare 6 cursor rules from other repositories ↓
Install with agentmods
npx agentmods add rules/2154355737/jieshenshequ/04-backend-rust
Install

Getting it into your agent

One page per mod, every tool's command on it. A separate URL per tool would split the same page into five that compete with each other.

Clone the repo
git clone --depth 1 https://github.com/2154355737/JieShenSheQu

Made for: Cursor.

Wrote this? Show the measurements

A badge with what this costs and how it scanned, read live from this page, so it follows the numbers instead of freezing them. Markdown for a README, HTML for a documentation site or a project page.

agentmods badge for 04-backend-rust

README.md
[![agentmods](https://agentmods.dev/badge/rules/2154355737/jieshenshequ/04-backend-rust.svg)](https://agentmods.dev/rules/2154355737/jieshenshequ/04-backend-rust)
Your own site
<a href="https://agentmods.dev/rules/2154355737/jieshenshequ/04-backend-rust"><img src="https://agentmods.dev/badge/rules/2154355737/jieshenshequ/04-backend-rust.svg" alt="Measured on agentmods" height="20"></a>
Per session 0 Nothing until a file matches its globs; then the whole rule loads.
When invoked 3,267 The whole file, excluding the scripts and references it only reads on demand.
Security scan A 0 findings. A grade says what 26 rules found in the file — not that it is safe.
Origin original No closer match found in the catalogue.
Token cost

What it costs to keep this loaded

Counted locally with the o200k_base tokenizer, which is exact for GPT models; Claude uses its own tokenizer and its counts differ. Treat this as one consistent yardstick across the catalogue rather than a bill. Prices are per million input tokens.

ModelPer sessionOnce invoked
Fable 5.1 $0.00000 $0.03267
Opus 5 $0.00000 $0.01633
Sonnet 5 $0.00000 $0.00653
Haiku 4.5 $0.00000 $0.00327

Measured 8d ago against content hash e57a3a6e2ceb, method: parsed. Prices are Anthropic first-party input rates as of 2026-09-08, from the pricing page.

Security

Grade A, and why

04-backend-rust scanned grade A with 0 findings against 26 rules in 11 categories — prompt injection, anti-refusal, data exfiltration, privilege escalation, supply chain, agent snooping, system-prompt leakage, SSRF and excessive agency — measured 8d ago.

A static scan of the body, not an audit. Every finding is printed with the line that produced it so you can judge whether it matters here. A mod is markdown that instructs an agent; that is exactly why what it instructs is worth reading.

Nothing flagged

None of the 26 patterns this scan looks for appear in this file: no shell pipes, no recursive deletes, no credential paths, no hidden text, no instruction-override or anti-refusal phrasing, no agent-config snooping. That is not a guarantee, it is the absence of the things that are checkable.

App_v2/jieshengshequ-app/.cursor/rules/04-backend-rust.mdc · 483 lines

How it starts

The opening of the file, as written. The whole thing — 483 lines — stays where its author put it; the contents beside it link to each section on GitHub.

Rust后端开发规范

🏗️ 项目结构

参考: APP_HouDuan/src

src/
├── api/v1/              # API路由处理器
├── models/              # 数据模型
├── repositories/        # 数据访问层
├── services/            # 业务逻辑层
├── middleware/          # 中间件
├── utils/               # 工具函数
├── bootstrap/           # 应用启动配置
└── main.rs              # 入口文件

📦 依赖管理

参考: APP_HouDuan/Cargo.toml

核心依赖

  • actix-web 4.4: Web框架
  • rusqlite 0.29: SQLite数据库
  • serde + serde_json: 序列化/反序列化
  • jsonwebtoken 9.2: JWT认证
  • bcrypt 0.15: 密码哈希
  • chrono 0.4: 日期时间处理
  • log + env_logger: 日志记录

🎯 分层架构实现

1. Model层 (数据模型)

参考: APP_HouDuan/src/models

// ✅ 推荐: 定义清晰的数据模型
use serde::{Deserialize, Serialize};
use chrono::{DateTime, Utc};

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct User {
    pub id: i64,
    pub username: String,
    pub email: String,
    #[serde(skip_serializing)]
    pub password_hash: String,
    pub role: UserRole,
    pub avatar: Option<String>,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum UserRole {
    Admin,
    User,
    Guest,
}

// 请求DTO
#[derive(Debug, Deserialize)]
pub struct CreateUserRequest {
    pub username: String,
    pub email: String,
    pub password: String,
}

// 响应DTO
#[derive(Debug, Serialize)]
pub struct UserResponse {
    pub id: i64,
    pub username: String,
    pub email: String,
    pub role: UserRole,
    pub avatar: Option<String>,
}

impl From<User> for UserResponse {
    fn from(user: User) -> Self {
        Self {
            id: user.id,
            username: user.username,
            email: user.email,
            role: user.role,
            avatar: user.avatar,
        }
    }
}

2. Repository层 (数据访问)

参考: APP_HouDuan/src/repositories

// ✅ 推荐: 使用Repository模式封装数据访问
use rusqlite::{Connection, params, Result};
use std::sync::{Arc, Mutex};

pub struct UserRepository {
    conn: Arc<Mutex<Connection>>,
}

impl UserRepository {
    pub fn new(conn: Arc<Mutex<Connection>>) -> Self {
        Self { conn }
    }
    
    pub fn find_by_id(&self, id: i64) -> Result<Option<User>> {
        let conn = self.conn.lock().unwrap();
        let mut stmt = conn.prepare(
            "SELECT id, username, email, password_hash, role, avatar, 
             created_at, updated_at FROM users WHERE id = ?"
        )?;
        
        let user = stmt.query_row(params![id], |row| {
            Ok(User {
                id: row.get(0)?,
                username: row.get(1)?,
                email: row.get(2)?,
                password_hash: row.get(3)?,
                role: row.get(4)?,
                avatar: row.get(5)?,
                created_at: row.get(6)?,
                updated_at: row.get(7)?,
            })
        }).optional()?;
        
        Ok(user)
    }
    
    pub fn find_by_username(&self, username: &str) -> Result<Option<User>> {
        let conn = self.conn.lock().unwrap();
        let mut stmt = conn.prepare(
            "SELECT id, username, email, password_hash, role, avatar, 
             created_at, updated_at FROM users WHERE username = ?"
        )?;
        
        let user = stmt.query_row(params![username], |row| {
            // 映射逻辑...
        }).optional()?;
        
        Ok(user)
    }
    
    pub fn create(&self, req: CreateUserRequest, password_hash: String) -> Result<User> {
        let conn = self.conn.lock().unwrap();
        
        conn.execute(
            "INSERT INTO users (username, email, password_hash, role, created_at, updated_at) 
             VALUES (?1, ?2, ?3, ?4, datetime('now'), datetime('now'))",
            params![req.username, req.email, password_hash, "user"],
        )?;
        
        let id = conn.last_insert_rowid();
        self.find_by_id(id)?.ok_or_else(|| {
            rusqlite::Error::QueryReturnedNoRows
        })
    }
    
    pub fn update(&self, id: i64, user: UpdateUserRequest) -> Result<User> {
        let conn = self.conn.lock().unwrap();
        
        conn.execute(
            "UPDATE users SET email = ?1, avatar = ?2, updated_at = datetime('now') 
             WHERE id = ?3",
            params![user.email, user.avatar, id],
        )?;
        
        self.find_by_id(id)?.ok_or_else(|| {
            rusqlite::Error::QueryReturnedNoRows
        })
    }
}

Read the full file on GitHub · 483 lines

Changes

What this file has done since we first saw it

Hashed on every crawl. A supply-chain change to an agent config is a question of when, not whether, so the history is kept rather than the latest state alone.

  1. 8d ago First seen · 483 lines · 0 tokens per session scan A e57a3a6e2ceb

Subscribe to this mod's changes

04-backend-rust is a cursor rule published in the GitHub repository 2154355737/JieShenSheQu (2 stars, last pushed 11mo ago), licensed MIT. It costs nothing until one of its globs matches a file; then it loads 3,267 tokens. A static security scan graded it A with 0 findings. No closer match exists in the catalogue, so it is treated as the original; first seen 2026-08-31.