如果你是编程新手,或者已经熟悉其他语言但想尝试 Rust语言Web开发,那么你来对地方了!本教程将手把手带你用 Rust 构建一个简单的 Web 应用,即使你是完全的小白,也能轻松上手。
Rust语言入门 虽然有一定学习曲线,但它以内存安全、高性能和并发能力著称。对于现代 Web 后端服务来说,这些特性非常关键。Rust 的生态系统近年来也快速发展,出现了多个成熟的 Web 框架,比如 Actix Web、Warp 和 Axum。
首先,你需要在电脑上安装 Rust。打开终端(Windows 用户使用 PowerShell 或 CMD),运行以下命令:
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh 安装完成后,验证是否成功:
rustc --version 你应该会看到类似 rustc 1.70.0 (... 的输出。
我们将使用 Actix Web —— 一个高性能、易用的 Rust Web 框架。它非常适合 Web框架Rust 初学者。
首先,创建一个新的 Rust 项目:
cargo new rust-web-democd rust-web-demo 然后,编辑 Cargo.toml 文件,在 [dependencies] 部分添加 Actix Web 依赖:
[dependencies]actix-web = "4" 打开 src/main.rs 文件,替换为以下代码:
use actix_web::{web, App, HttpResponse, HttpServer, Result};async fn hello() -> Result<HttpResponse> { Ok(HttpResponse::Ok().body("Hello from Rust Web! 🦀"))}#[actix_web::main]async fn main() -> std::io::Result<()> { println!("🚀 Server running at http://127.0.0.1:8080"); HttpServer::new(|| { App::new().route("/", web::get().to(hello)) }) .bind("127.0.0.1:8080")? .run() .await} 这段代码做了三件事:
hello,返回 “Hello from Rust Web!”HttpServer 监听本地 8080 端口/ 映射到 hello 函数在项目目录下执行:
cargo run 你会看到控制台输出:🚀 Server running at http://127.0.0.1:8080。打开浏览器访问该地址,就能看到欢迎信息!
现代 Web 开发离不开 API。我们来添加一个返回 JSON 的接口:
use actix_web::{web, App, HttpResponse, HttpServer, Result};use serde::{Deserialize, Serialize};#[derive(Serialize)]struct Greeting { message: String,}async fn json_hello() -> Result<HttpResponse> { let greeting = Greeting { message: "Welcome to Rust backend development!".to_string(), }; Ok(HttpResponse::Ok().json(greeting))}#[actix_web::main]async fn main() -> std::io::Result<()> { println!("🚀 Server running at http://127.0.0.1:8080"); HttpServer::new(|| { App::new() .route("/", web::get().to(|| async { "Hello from Rust Web! 🦀" })) .route("/api/hello", web::get().to(json_hello)) }) .bind("127.0.0.1:8080")? .run() .await} 别忘了在 Cargo.toml 中添加 serde 支持:
[dependencies]actix-web = "4"serde = { version = "1.0", features = ["derive"] } 现在访问 http://127.0.0.1:8080/api/hello,你会看到一个 JSON 响应!这展示了如何用 Rust 构建 RESTful API,非常适合 后端开发Rust 场景。
恭喜你!你已经完成了 Rust Web 开发的第一步。通过本教程,你学会了:
Rust 的类型安全和零成本抽象使其成为构建可靠、高性能 Web 服务的理想选择。继续深入学习 Rust语言Web开发,你将能构建更复杂的系统,如数据库集成、用户认证、WebSocket 实时通信等。
下一步建议:阅读 Actix Web 官方文档,或尝试其他框架如 Axum(由 Tokio 团队维护)。
本文由主机测评网于2025-12-24发表在主机测评网_免费VPS_免费云服务器_免费独立服务器,如有疑问,请联系我们。
本文链接:https://www.vpshk.cn/20251212205.html