Learn Rust Coding · 课时

Axum 路由

处理器与路由

第 1 / 4 课13 个步骤

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

Axum 是什么

Axum 是 Tokio 团队开发的简洁易用的异步 Web 框架。它构建于 tower 和 hyper 之上。

  • 处理函数是普通的异步函数
  • 路由由类型驱动,并且可以组合
  • 运行在 Tokio 运行时上

处理函数就是一个函数

Axum 的处理函数是一个异步函数,它会返回可转换为响应的内容,例如 &str 或 String。

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

构建 Router

Router 会将路径映射到处理函数。使用 route,并传入 get 这样的 HTTP 方法过滤器。

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

async fn hello() -> &'static str { "Hello" }

fn app() -> Router {
    Router::new().route("/", get(hello))
}

启动服务器

绑定 TCP 监听器并提供路由服务。#[tokio::main] 宏会设置异步运行时。

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

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

多个路由

链式调用 route,即可在一个路由器上注册多个端点。

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

fn app() -> Router {
    Router::new()
        .route("/", get(|| async { "home" }))
        .route("/about", get(|| async { "about" }))
}

不同的 HTTP 方法

使用 get(...).post(...) 在同一路径上组合多个方法处理函数。每种方法都会路由到自己的处理函数。

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

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

路径参数

使用 {name} 片段捕获 URL 的部分内容,并通过 Path 提取器读取它们。

use axum::extract::Path;

async fn show(Path(id): Path<u32>) -> String {
    format!("item {}", id)
}

使用普通 Rust 对路由建模

路由的核心是将路径映射到响应。这个可运行模型不依赖框架,却体现了这一思想。

fn route(path: &str) -> &str {
    match path {
        "/" => "home",
        "/about" => "about page",
        _ => "404 not found",
    }
}

fn main() {
    println!("{}", route("/"));
    println!("{}", route("/about"));
    println!("{}", route("/missing"));
}

嵌套路由器

使用 nest 将子路由器挂载到某个前缀下,从而组合出更大的应用。

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

fn api() -> Router {
    Router::new().route("/users", get(|| async { "users" }))
}

fn app() -> Router {
    Router::new().nest("/api", api())
}

备用处理函数

使用 fallback 定义未匹配路由时的行为。它非常适合自定义 404 页面。

use axum::{Router, http::StatusCode};

async fn not_found() -> (StatusCode, &'static str) {
    (StatusCode::NOT_FOUND, "nothing here")
}

fn app() -> Router {
    Router::new().fallback(not_found)
}

返回状态代码

处理函数可以返回 (StatusCode, body) 元组,以精确控制响应状态。

use axum::http::StatusCode;

async fn create() -> (StatusCode, &'static str) {
    (StatusCode::CREATED, "created")
}

快速检查

测试您对 Axum 路由的理解。

总结

您已经学习了 Axum 路由的基础知识:

  • 处理函数是返回响应的异步函数
  • Router::new().route(path, get(handler)) 会注册端点
  • Path 会捕获 URL 片段
  • nest、fallback 和状态元组可以构建应用

下一步:提取器会解析传入的请求。

免费开始

用 AI 导师学习 Rust — 免费

在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。

课程
39
课程
144

常见问题解答

「Axum 路由」课时是免费的吗?

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

「Axum 路由」这节课中我会学到什么?

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

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

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

「Axum 路由」课时需要多长时间?

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

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

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

此课程中的所有课时

  1. Axum 路由
  2. 提取器
  3. JSON 与状态
  4. 中间件
← 返回 Learn Rust Coding