使用Rhai和Actix Web在Rust中构建REST API

作者:API传播员 · 2025-12-06 · 阅读时间:6分钟

Rhai 是一种高级脚本语言,允许开发者通过脚本编写应用程序的逻辑,并将这些脚本嵌入到 Rust 程序中执行。相比 Rust,Rhai 的脚本更易于理解,因此能够更轻松地创建复杂的程序。

在本文中,我们将学习如何在 Rust 中嵌入 Rhai 脚本,并结合 Actix Web 框架构建 RESTful API。以下是本文的主要内容:


Rhai 简介及其与 Rust 的结合

Rhai 的名称来源于 C++ 的脚本语言 ChaiScript。与 ChaiScript 类似,Rhai 也可以嵌入到主语言中(Rust),并通过简单易懂的脚本抽象复杂的算法。Rhai 和 ChaiScript 都采用类似 JavaScript 的语法,为开发者提供了一种安全的方式将脚本集成到主程序中。

使用 Rhai 的优势

  1. 性能优越:与其他脚本语言(如 JavaScript、Lua 和 Python)相比,Rhai 的执行速度更快。
  2. 动态类型:支持动态类型,提供了更高的灵活性并降低了复杂性。
  3. 高级抽象:Rhai 是一种比 Rust 更高级的语言,开发者可以通过它轻松实现复杂算法。
  4. 内存安全:Rhai 脚本在沙盒环境中运行,不会影响 Rust 程序的内存安全性。

在 Rust 中运行 Rhai 脚本

以下是将 Rhai 脚本嵌入到 Rust 程序中的步骤:

添加 Rhai 依赖

在项目的 Cargo.toml 文件中添加以下内容:

[dependencies]
rhai = "1.6.1"

然后运行以下命令构建项目并下载依赖:

cargo build

创建示例程序

  1. 初始化一个新的 Rust 项目:

    cargo init rhai_tutorial --bin
  2. 在项目的 main.rs 文件中添加以下代码:

   use rhai::{Engine};

   fn main() {
       let engine = Engine::new();
       let result = engine.eval_file::("src/my_script.rhai".into()).unwrap();
       println!("{}", result);
   }
  1. src 文件夹中创建一个名为 my_script.rhai 的文件,并添加以下脚本:
   fn hello(name) {
       return "Hello, " + name;
   }

   hello("World!");
  1. 运行项目:

    cargo run

    输出结果应为:

    Hello, World!

通过上述步骤,我们成功在 Rust 程序中嵌入了 Rhai 脚本,并实现了一个简单的 "Hello, World!" 示例。


使用 Actix Web 构建 RESTful API

Actix Web 是一个高性能的 Rust Web 框架,适用于构建 RESTful API。以下是使用 Actix Web 的基本步骤:

添加 Actix Web 依赖

Cargo.toml 文件中添加以下内容:

[dependencies]
actix-web = "4.0.1"

然后运行以下命令下载依赖:

cargo build

创建简单的 RESTful API

以下是一个简单的 API 示例,它在根路径 / 返回 "Hello, World!":

use actix_web::{HttpServer, App, get, Responder};

#[get("/")]
async fn greet() -> impl Responder {
    "Hello, World!"
}#[actix_web::main]
async fn main() -> std::io::Result {    HttpServer::new(|| {        App::new().service(greet)
    })
    .bind(("127.0.0.1", 8080))?
    .run()
    .await
}

运行程序后,访问 http://localhost:8080/,即可看到 "Hello, World!" 的响应。


动态路由示例

Actix Web 支持动态路由,以下是一个示例程序,它会根据 URL 的最后一段动态生成响应:

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

#[get("/{name}")]
async fn greet(path: web::Path) -> impl Responder {
    let name = path.into_inner().0;
    format!("Hello, {name}!")
}#[actix_web::main]
async fn main() -> std::io::Result {    HttpServer::new(|| {        App::new().service(greet)
    })
    .bind(("127.0.0.1", 8080))?
    .run()
    .await
}

例如,访问 http://localhost:8080/humans,程序会返回 "Hello, humans!"。


将 Rhai 与 Actix Web 结合

通过将 Rhai 与 Actix Web 结合,我们可以在 RESTful API 中使用 Rhai 脚本处理逻辑。以下是一个示例项目:

添加依赖

Cargo.toml 文件中添加以下内容:

[dependencies]
actix-web = "4.0.1"
rhai = "1.6.1"

运行以下命令构建项目:

cargo build

实现 API 逻辑

以下代码实现了两个端点:/multiply/{num1}/{num2}/add/{num1}/{num2},分别用于乘法和加法运算:

    App::new()
.service(multiply)
.service(add)
})
.bind(("127.0.0.1", 8080))?
.run()
.await

}

#[get("/multiply/{num1}/{num2}")]
async fn multiply(path: Path) -> impl Responder {
let (num1, num2) = path.into_inner();
let mut engine = Engine::new();

engine.register_fn("num1", move || num1);
engine.register_fn("num2", move || num2);

let result = engine.eval_file::("src/multiply.rhai".into()).unwrap();
format!("{result}")
}

#[get("/add/{num1}/{num2}")]
async fn add(path: Path) -> impl Responder {
let (num1, num2) = path.into_inner();
let mut engine = Engine::new();

engine.register_fn("num1", move || num1);
engine.register_fn("num2", move || num2);

let result = engine.eval_file::("src/add.rhai".into()).unwrap();
format!("{result}")
}

#[actix_web::main]
async fn main() -> std::io::Result {

HttpServer::new(|| {

App::new()
.service(multiply)
.service(add)
})
.bind(("127.0.0.1", 8080))?
.run()
.await
}

创建 Rhai 脚本

src 文件夹中创建以下两个文件:

  1. multiply.rhai
   fn multiply(num1, num2) {
       return num1 * num2;
   }

   let num1 = num1();
   let num2 = num2();   multiply(num1, num2);
  1. add.rhai
   fn add(num1, num2) {
       return num1 + num2;
   }

   let num1 = num1();
   let num2 = num2();   add(num1, num2);

运行程序后,访问 http://localhost:8080/add/5/15,结果应为 "20"。


总结

本文介绍了如何使用 Rhai 和 Actix Web 在 Rust 中构建 RESTful API。通过 Rhai 的脚本能力和 Actix Web 的高性能框架,开发者可以轻松实现复杂的逻辑并将其嵌入到 Rust 应用中。希望本文对您有所帮助!

原文链接: https://blog.logrocket.com/building-rest-api-rust-rhai-actix-web/