在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
,即可看到相应内容。