溫馨提示×

如何在Ubuntu上使用Rust進行Web開發

小樊
53
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
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女