在Ubuntu上使用Rust進行Web開發,可參考以下步驟:
打開終端,依次輸入以下命令安裝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
可配置國內鏡像源加速下載,如使用清華大學的鏡像源。
使用Cargo創建新項目,例如cargo new rust_web_app,然后進入項目目錄cd rust_web_app。
編輯Cargo.toml文件,在[dependencies]部分添加Web框架依賴,如Actix - web:
[dependencies]
actix-web = "4.0"
在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
}
在項目目錄下運行cargo run,然后在瀏覽器中訪問http://127.0.0.1:8080,即可看到相應內容。