0Pricing
Learn Rust Coding · 课时

项目设置

构建 API 结构

项目设置 是 CoddyKit 上的免费 Learn Rust Coding 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Learn Rust Coding 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Learn Rust Coding 课程共包含 4 节课。

使用 Rust 构建 REST API

在本课程中,您将使用 Rust 构建一个小型REST API。我们使用Axum Web 框架,它构建于 Tokio(异步运行时)和 Tower(中间件)之上。它易于使用、类型安全,并且在生产环境中得到广泛应用。

本课首先设置项目结构,后续课程将在此基础上添加路由、模型、数据库和测试。

创建项目

从 Cargo 开始。二进制项目会为您提供 src/main.rs 入口点:

  • cargo new rest_api 创建文件夹。
  • cd rest_api 进入该文件夹。
  • cargo run 构建并运行项目。

这些是 shell 和 cargo 命令,并不是可以运行的 Rust 代码片段。

// terminal
// cargo new rest_api
// cd rest_api
// cargo run

添加依赖

Axum API 需要在 Cargo.toml 中添加几个 crate:

  • axum 用于路由和处理函数。
  • tokio 用于异步运行时。
  • serde 用于 JSON 序列化。
// Cargo.toml
// [dependencies]
// axum = "0.7"
// tokio = { version = "1", features = ["full"] }
// serde = { version = "1", features = ["derive"] }
// serde_json = "1"

异步运行时

Web 服务器需要同时处理许多连接,因此 Axum 采用异步方式。#[tokio::main] 注解会启动 Tokio 运行时,将异步 main 转换为真正的入口点。每个处理函数都可以使用 .await 执行非阻塞 I/O。

// src/main.rs
use tokio;

#[tokio::main]
async fn main() {
    println!("runtime started");
}

最小服务器

最小的 Axum 应用会构建一个 Router、绑定 TCP 监听器并提供服务。单个路由将 GET / 映射到一个返回字符串的处理函数。处理函数本质上只是异步函数,其返回值实现了 IntoResponse。

use axum::{routing::get, Router};

#[tokio::main]
async fn main() {
    let app = Router::new().route("/", get(root));
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
        .await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

async fn root() -> &'static str {
    "Hello, API!"
}

路由的工作方式

Router 会将路径和 HTTP 方法映射到处理函数。链式调用 .route(path, method(handler)) 可以注册端点。get、post、put 和 delete 等方法辅助函数来自 axum::routing。您可以在同一路径上组合多个方法。

use axum::{routing::{get, post}, Router};

async fn list() -> &'static str { "list" }
async fn create() -> &'static str { "created" }

fn build_router() -> Router {
    Router::new()
        .route("/items", get(list).post(create))
        .route("/health", get(|| async { "ok" }))
}

推荐的模块布局

随着 API 不断扩展,请将代码拆分到多个模块中,而不要全部放在一个庞大的 main.rs 里:

  • main.rs — 启动和服务器组装。
  • routes.rs — 路由定义。
  • handlers.rs — 请求处理函数。
  • models.rs — 数据结构。

这种拆分能让每个文件各司其职,并便于测试。

// src/main.rs
mod routes;
mod handlers;
mod models;

#[tokio::main]
async fn main() {
    let app = routes::build();
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
        .await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

共享应用状态

大多数 API 都需要共享状态,例如数据库连接池或内存存储。Axum 通过路由上的 .with_state(state) 保存这些状态。处理函数通过 State 提取器接收状态。状态必须实现 Clone;可变数据则应使用 Arc 和锁进行封装。

use axum::{routing::get, Router, extract::State};
use std::sync::{Arc, Mutex};

type Db = Arc<Mutex<Vec<String>>>;

async fn count(State(db): State<Db>) -> String {
    let n = db.lock().unwrap().len();
    format!("{} items", n)
}

fn build(db: Db) -> Router {
    Router::new().route("/count", get(count)).with_state(db)
}

返回 JSON

要发送 JSON,请将可序列化的值封装在 axum::Json 中。使用 serde 为结构体派生 Serialize 后,Axum 会自动设置正确的内容类型和正文。

use axum::Json;
use serde::Serialize;

#[derive(Serialize)]
struct Status {
    service: String,
    healthy: bool,
}

async fn health() -> Json<Status> {
    Json(Status { service: "api".into(), healthy: true })
}

配置和端口

在演示中将端口硬编码没有问题,但实际服务应从环境中读取配置。请使用 std::env::var 并提供默认值。这样无需重新编译就能更改绑定地址,也能更好地配合容器使用。

use std::env;

async fn main_inner() {
    let port = env::var("PORT").unwrap_or_else(|_| "3000".to_string());
    let addr = format!("0.0.0.0:{}", port);
    println!("binding to {}", addr);
    // bind and serve with addr ...
}

整合启动设置

完整的启动流程需要将各部分连接起来:使用路由和共享状态构建路由器,读取端口,绑定监听器,然后提供服务。有了这个基本框架,后续课程就可以添加真实的端点、模型和持久化功能。

use axum::{routing::get, Router};
use std::sync::{Arc, Mutex};

#[tokio::main]
async fn main() {
    let db = Arc::new(Mutex::new(Vec::<String>::new()));
    let app = Router::new()
        .route("/health", get(|| async { "ok" }))
        .with_state(db);
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
        .await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

快速检查

测试您对项目设置的理解。

总结

您完成了 Rust REST API 项目的设置:

  • 使用 cargo new,并添加 axum、tokio 和 serde。
  • #[tokio::main] 提供异步运行时。
  • Router 将路径和方法映射到异步处理函数。
  • 使用 .with_state 和 State 提取器共享数据。
  • 将代码拆分为路由、处理函数和模型模块,并从环境中读取端口。

常见问题解答

「项目设置」课时是免费的吗?

是的 — 「项目设置」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Learn Rust Coding 课程的其余内容,请升级到 CoddyKit PRO。 Learn Rust Coding 课程共包含 4 节课。

「项目设置」这节课中我会学到什么?

构建 API 结构 你通过在浏览器中直接运行的动手代码来练习 Learn Rust Coding,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Learn Rust Coding 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Learn Rust Coding 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。

「项目设置」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Learn Rust Coding 课中编写并运行代码吗?

能。每节 Learn Rust Coding 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 项目设置
  2. 端点与模型
  3. 数据库集成
  4. 测试 API
← 返回 Learn Rust Coding