ubuntu

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

小樊
48
2025-09-12 19:56:14
栏目: 编程语言

在Ubuntu上使用Rust进行Web开发,可参考以下步骤:

安装Rust环境

打开终端,依次输入以下命令安装Rust和Cargo:

sudo apt update
sudo apt install curl build-essential gcc make
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
source $HOME/.cargo/env

可配置国内镜像源加速下载,如使用清华大学的镜像源。

创建Web项目

使用Cargo创建新项目,例如cargo new rust_web_app,然后进入项目目录cd rust_web_app

添加依赖

编辑Cargo.toml文件,在[dependencies]部分添加Web框架依赖,如Actix - web:

[dependencies]
actix-web = "4.0"

编写Web代码

src/main.rs中编写代码,以Actix - web为例,创建一个简单的Hello World应用:

use actix_web::{get, web, App, HttpServer, HttpResponse};

#[get("/")]
async fn index() -> HttpResponse {
    HttpResponse::Ok().body("Hello, Rust Web!")
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new()
            .service(index)
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}

运行Web应用

在项目目录下运行cargo run,然后在浏览器中访问http://127.0.0.1:8080,即可看到相应内容。

0
看了该问题的人还看了