如何使用 Rust 和 Actix 搭建 Web 服务器

0 股票
0
0
0
0

介绍

在本教程中,您将学习如何在 DigitalOcean Droplet 上使用 Rust 和 Actix-web 框架构建 Web 服务器。您将设置核心服务器并创建路由来管理一个简单的待办事项列表,该列表支持常见的 RESTful 操作,例如检索和创建待办事项。.

先决条件

开始之前,请确保您已准备好以下物品:

  • DigitalOcean 云账户 使液滴旋转。.
  • Ubuntu Droplet 已启动并运行。.
  • Rust 已安装在 Droplet 上。.
  • 熟悉 Rust 的基本原理,包括变量、函数和属性。.

步骤 1 – 设置 Ubuntu Droplet

通过 SSH 连接到您的 DigitalOcean Droplet:打开终端并使用以下命令通过 SSH 连接到您的 Droplet。将 your_username 替换为您的实际用户名,将 your_droplet_ip 替换为您的 Droplet IP 地址:

ssh your_username@your_droplet_ip

更新软件包列表:登录后,请更新软件包列表,以确保您拥有最新的可用软件包信息:

sudo apt update

安装 Rust:要安装 Rust,请使用以下命令,该命令将下载并运行 Rust 安装脚本:

curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

请按照屏幕上的说明完成安装。安装完成后,您可能需要重启终端或运行以下命令:

source $HOME/.cargo/env

安装必要的库:安装构建 Rust 应用程序所需的库。您可以使用以下命令安装 build-essential 和 libssl-dev:

sudo apt install build-essential libssl-dev

验证 Rust 安装:要验证 Rust 是否已正确安装,请检查版本:

rustc --version

安装 Cargo(Rust 包管理器):Cargo 会随 Rust 自动安装。您可以通过检查版本来验证其是否已安装:

cargo --version

步骤二——启动项目

让我们使用 payload 创建一个新的 Rust 项目 sammy_todos。

cargo new sammy_todos

然后找到 Cargo.toml 文件。进入 Rust 项目的根目录。Cargo.toml 文件位于创建项目的同一目录下(例如,sammy_todos)。您可以使用以下命令切换到项目目录:

cd sammy_todos/
ls

以下是自动生成的 Rust 项目文件:

Output
Cargo.toml src

在 Cargo.toml 文件中添加 actix-web 和 serde 作为依赖项。其中,serde 用于序列化和反序列化。.

vi Cargo.toml

并在 dependencies 下添加以下几行。.

[dependencies]
actix-web = "4.0"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"

现在使用以下命令下载并编译依赖项:

cargo build

步骤 3 – 创建基本服务器

在 main.rs 文件中添加以下代码以启动主服务器。您需要进入项目目录下的 src 目录。.

use actix_web::{get, App, HttpServer, HttpResponse, Responder,web};
#[get("/")]
async fn index() -> impl Responder {
HttpResponse::Ok().body("Welcome to the Sammy Todo API!")
}
#[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

要测试服务器,请打开一个新的终端会话并运行以下命令:

curl http://127.0.0.1:8080

您应该会收到以下回复:

Output
Welcome to the Sammy Todo API!

步骤 4 – 添加待办事项模型

Todo 模型用于序列化请求和响应。请将以下代码添加到 main.rs 文件中。.

use serde::{Serialize, Deserialize};
#[derive(Serialize, Deserialize)]
struct Todo {
id: i32,
title: String,
completed: bool,
}

步骤 5 – 执行 创建待办事项

这个 API 会创建待办事项,它是一个虚拟 API,只会返回你的待办事项,但你可以用数据库来实现它,使其持久化。.

#[get("/todos")]
async fn create_todo(todo: web::Json<Todo>) -> impl Responder {
HttpResponse::Ok().body(serde_json::to_string(&todo).unwrap())
}

步骤 6 – 运行 GetTodo

此 API 返回 id 为:的待办事项

#[get("/todos/{id}")]
async fn get_todo(id: web::Path<i32>) -> impl Responder {
let todo = Todo {
id: id.into_inner(),
title: "Learn Actix-Web".to_string(),
completed: false,
};
HttpResponse::Ok().body(serde_json::to_string(&todo).unwrap())
}

将服务连接到您的服务器

Rust 服务器的 main.rs 文件内容如下:

use actix_web::{get, App, HttpServer, HttpResponse, Responder, web};
#[get("/")]
async fn index() -> impl Responder {
HttpResponse::Ok().body("Welcome to the Sammy Todo API!")
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
App::new()
.service(index)
.service(get_todo)
.service(create_todo)
})
.bind("127.0.0.1:8080")?
.run()
.await
}
use serde::{Serialize, Deserialize}; // Added Deserialize to imports
#[derive(Serialize, Deserialize)] // Ensure Deserialize is imported
struct Todo {
id: i32,
title: String,
completed: bool,
}
#[get("/todos")]
async fn create_todo(todo: web::Json<Todo>) -> impl Responder {
HttpResponse::Ok().body(serde_json::to_string(&todo).unwrap())
}
#[get("/todos/{id}")]
async fn get_todo(id: web::Path<i32>) -> impl Responder {
let todo = Todo {
id: id.into_inner(),
title: "Learn Actix-Web".to_string(),
completed: false,
};
HttpResponse::Ok().body(serde_json::to_string(&todo).unwrap())
}

现在,您可以使用 curl 发送 POST 请求来测试它:

curl -X POST -H "Content-Type: application/json" -d '{"title": "Buy groceries"}' http://127.0.0.1:8080/todos

结果

恭喜!您已成功使用 Rust 和 Actix 搭建了一个基本的 Web 服务器。本教程将教您如何创建用于检索和创建待办事项的端点,为构建更复杂的应用程序奠定坚实的基础。为了进一步增强您的应用程序,您可以集成一个数据库解决方案来实现数据持久化,从而高效地存储和管理待办事项。.

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

您可能也喜欢