一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

如何在Ubuntu中使用Rust进行Web开发

时间:2026-08-17 09:24:52 编辑:袖梨 来源:一聚教程网

在Ubuntu中使用Rust进行Web开发的完整流程

如何在Ubuntu中使用Rust进行Web开发

1. 准备开发环境

在Ubuntu上,首先需要安装Rust工具链和必要的系统依赖:

  1. 安装Rust:通过rustup脚本安装最新稳定版Rust(包含rustc编译器和Cargo包管理器):
    curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | shsource ~/.cargo/env# 初始化环境变量
    安装完成后,通过rustc --version验证是否成功。
  2. 安装系统依赖:Ubuntu需要build-essential工具链来编译原生扩展(如数据库驱动):
    sudo apt update && sudo apt install -y build-essential

2. 创建Rust项目

使用Cargo创建一个新的Web项目(以my_rust_web_app为例):

cargo new my_rust_web_appcd my_rust_web_app

Cargo会自动生成Cargo.toml(依赖管理)和src/main.rs(主程序)文件。

3. 选择Web框架

Rust生态中有4个主流Web框架,根据项目需求选择:

  1. Axum(推荐新手):由Tokio团队开发,基于Tokio异步运行时,无宏API、轻量级、生态丰富(支持中间件、JSON处理等)。
  2. Actix-web:高性能、成熟稳定,基于Actor模型,适合复杂企业级应用(如高并发API)。
  3. Warp:以“组合友好”著称,提供丰富的开箱即用功能(如路由、过滤、压缩),适合构建RESTful API或微服务。
  4. Rocket:对初学者最友好,语法简洁,但需启用Rust nightly版本(实验性),适合快速原型开发。

4. 添加框架依赖

以Axum为例,在Cargo.toml中添加核心依赖及工具库:

[dependencies]axum = "0.7"# Axum框架核心tokio = { version = "1.0", features = ["full"] }# 异步运行时serde = { version = "1.0", features = ["derive"] } # JSON序列化/反序列化serde_json = "1.0"# JSON处理tower-http = "0.4"# 高级中间件(如CORS、日志)

其他框架的依赖可参考官方文档(如Actix-web需添加actix-web = "4.0")。

5. 编写Web服务代码

以Axum为例,在src/main.rs中创建一个简单的HTTP服务器:

use axum::{routing::get,// 路由GET请求Router, // 路由容器Json, // JSON响应包装器};use serde::Serialize; // 结构体序列化use std::net::SocketAddr;// 定义响应数据结构#[derive(Serialize)]struct HelloWorld {message: String,}// 处理GET请求的异步函数async fn hello() -> Json<HelloWorld> {Json(HelloWorld {message: "Hello from Rust Web!".to_string(),})}#[tokio::main] // 异步运行时入口async fn main() {// 构建路由:将根路径"/"映射到hello函数let app = Router::new().route("/", get(hello));// 绑定地址(127.0.0.1:3000)并启动服务器let addr = SocketAddr::from(([127, 0, 0, 1], 3000));println!("Server running at http://{}", addr);axum::Server::bind(&addr).serve(app.into_make_service()).await.unwrap();}

代码说明:

  1. #[tokio::main]:标记异步主函数,使用Tokio运行时。
  2. Router::new().route():定义路由规则(GET请求映射到hello函数)。
  3. Json:将Rust结构体序列化为JSON响应。

6. 运行与测试

在项目根目录下执行以下命令启动服务器:

cargo run

终端输出Server running at http://127.0.0.1:3000后,打开浏览器或使用curl访问:

curl http://127.0.0.1:3000

将返回JSON响应:

{"message":"Hello from Rust Web!"}

7. 扩展功能(数据库/表单处理)

数据库集成(以PostgreSQL为例)

  1. 添加依赖:在Cargo.toml中添加sqlx(异步SQL库)和PostgreSQL驱动:
    sqlx = { version = "0.7", features = ["postgres", "runtime-tokio-native-tls", "macros"] }dotenv = "0.15" # 环境变量管理
  2. 创建.env文件存储数据库配置:
    DATABASE_URL=postgres://username:password@localhost/mydb
  3. 编写数据库查询代码(如获取用户列表):
    use sqlx::PgPool;use serde::Serialize;#[derive(Serialize)]struct User {id: i32,name: String,}async fn get_users(pool: PgPool) -> Result<Json<Vec<User>>, sqlx::Error> {let users = sqlx::query_as!(User,"SELECT id, name FROM users").fetch_all(&pool).await?;Ok(Json(users))}
  4. 修改路由以传递数据库连接池:
    use std::sync::Arc;use axum::extract::State;#[tokio::main]async fn main() {// 初始化数据库连接池let database_url = std::env::var("DATABASE_URL").expect("DATABASE_URL not set");let pool = PgPool::connect(&database_url).await.expect("Failed to connect to DB");let pool = Arc::new(pool);// 将连接池注入路由状态let app = Router::new().route("/users", get(get_users)).with_state(pool);// 启动服务器...}async fn get_users(State(pool): State<Arc<PgPool>>) -> Result<Json<Vec<User>>, sqlx::Error> {// 使用pool查询数据库...}

表单处理

使用serde解析POST请求中的表单数据(如登录表单):

use axum::{routing::post,Form,Json,};use serde::Deserialize;#[derive(Deserialize)]struct LoginForm {username: String,password: String,}async fn login(Form(login_data): Form<LoginForm>) -> Json<serde_json::Value> {// 验证用户名密码...Json(serde_json::json!({"status": "success","message": format!("Welcome, {}!", login_data.username)}))}// 在路由中添加POST路由let app = Router::new().route("/login", post(login));

8. 部署

Ubuntu上部署Rust Web应用通常使用Nginx反向隧道或Docker容器化:

  1. Nginx反向隧道:将Nginx作为反向代 理,转发请求到Rust应用(运行在3000端口):
    server {listen 80;server_name yourdomain.com;location / {proxy_pass http://127.0.0.1:3000;proxy_set_header Host $host;proxy_set_header X-Real-IP $remote_addr;}}
  2. Docker部署:编写Dockerfile构建镜像并运行容器:
    FROM rust:latestWORKDIR /appCOPY . .RUN cargo build --releaseCMD ["./target/release/my_rust_web_app"]
    构建并运行容器:
    docker build -t my_rust_app .docker run -p 3000:3000 my_rust_app

通过以上步骤,即可在Ubuntu上完成Rust Web应用的开发、测试与部署。根据项目需求选择合适的框架(如Axum适合快速开发,Actix-web适合高并发),并利用Rust生态中的工具(如sqlxserde)扩展功能。

热门栏目