在当今的系统编程领域,Rust 因其内存安全、零成本抽象和卓越的性能而备受青睐。如果你正打算使用 Rust 构建现代 Web 应用或 RESTful API,那么 Axum 框架是一个绝佳的选择。本文将带你从零开始,全面了解 Rust Axum框架入门 的全过程,即使你是编程小白,也能轻松上手!
Axum 是一个基于 tokio 和 hyper 构建的现代化 Web 框架,专为异步 Rust 设计。它以类型安全、组合性强和极简主义著称,非常适合构建高性能的 REST API 或微服务。
首先,确保你已安装 Rust。打开终端,运行以下命令:
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh 接着,创建一个新的 Rust 项目:
cargo new axum_hellocd axum_hello 打开 Cargo.toml 文件,在 [dependencies] 部分添加以下内容:
[dependencies]tokio = { version = "1", features = ["full"] }axum = "0.7" 这里我们启用了 tokio 的 full 特性以支持异步运行时。
现在,编辑 src/main.rs 文件,输入以下代码:
use axum::{ routing::get, Router,};use std::net::SocketAddr;#[tokio::main]async fn main() { // 构建路由 let app = Router::new().route("/", get(hello)); // 监听地址 let addr = SocketAddr::from(([127, 0, 0, 1], 3000)); println!("🚀 服务器运行在 http://{}", addr); // 启动服务器 axum::Server::bind(&addr) .serve(app.into_make_service()) .await .unwrap();}// 处理函数async fn hello() -> &'static str { "Hello, 欢迎学习 Rust Axum框架入门!"} 这段代码做了三件事:
hello,返回一段欢迎文本;Router::new() 创建路由,并将根路径 / 映射到 hello 函数;在终端中执行:
cargo run 看到输出 🚀 服务器运行在 http://127.0.0.1:3000 后,打开浏览器访问 http://127.0.0.1:3000,你将看到:
Hello, 欢迎学习 Rust Axum框架入门!
接下来,我们扩展应用,实现一个返回 JSON 数据的接口。修改 main.rs 如下:
use axum::{ routing::get, Router, Json,};use serde::{Deserialize, Serialize};use std::net::SocketAddr;#[derive(Serialize)]struct User { id: u32, name: String,}#[tokio::main]async fn main() { let app = Router::new() .route("/", get(hello)) .route("/user", get(get_user)); let addr = SocketAddr::from(([127, 0, 0, 1], 3000)); println!("🚀 服务器运行在 http://{}", addr); axum::Server::bind(&addr) .serve(app.into_make_service()) .await .unwrap();}async fn hello() -> &'static str { "Hello, 欢迎学习 Rust Axum框架入门!"}async fn get_user() -> Json { Json(User { id: 1, name: "张三".to_string(), })} 别忘了在 Cargo.toml 中添加 serde 依赖:
serde = { version = "1.0", features = ["derive"] } 重新运行 cargo run,访问 /user 路径,你将获得一个 JSON 响应:
{"id":1,"name":"张三"} 恭喜你!你已经成功完成了 Rust Axum框架入门 的第一步。通过本教程,你学会了如何搭建开发环境、创建基本路由、返回文本和 JSON 数据。这些是构建更复杂 Web 应用的基础。
无论是开发 Axum Web开发教程 中提到的 REST API,还是探索 Rust构建REST API 的高级特性(如中间件、错误处理、数据库集成等),Axum 都能为你提供强大而简洁的工具链。
记住,最好的学习方式就是动手实践。尝试添加更多路由、处理 POST 请求、连接数据库,逐步提升你的 Axum初学者指南 技能树吧!
🌟 Happy Coding with Rust and Axum! 🌟
本文由主机测评网于2025-12-04发表在主机测评网_免费VPS_免费云服务器_免费独立服务器,如有疑问,请联系我们。
本文链接:https://www.vpshk.cn/2025122850.html