初始化项目

cargo new acix-rhai-web

依赖(Cargo.toml)

[package]
name = "actix-sim-yt"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

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

rhai

Rhai是一种高级脚本语言,允许你在脚本中编写应用程序的逻辑。这些脚本可以被嵌入到Rust程序中并在其中执行。

项目结构

main.rs

use actix_web::{
    HttpServer,
    get,
    App,
    web::Path,
    Responder
};
use rhai::Engine;
// 提供get接口,http://localhost:8080/multiply/2/3
// 乘法接口
#[get("/multiply/{num1}/{num2}")]
async fn multiply(path: Path<(i64,i64)>)->impl Responder{
    let (num1,num2) = path.into_inner();
    let mut engine = Engine::new();
    // 暴露变量给rhai
    engine.register_fn("num1",move || num1);
    engine.register_fn("num2",move || num2);
    let res = engine.eval_file::<i64>("src/multiply.rhai".into()).unwrap();
    format!("{res}")
}
// 加法接口
#[get("/add/{num1}/{num2}")]
async fn add(path: Path<(i64,i64)>)->impl Responder{
    let (num1,num2) = path.into_inner();
    let mut engine = Engine::new();
    // 暴露变量给rhai
    engine.register_fn("num1",move || num1);
    engine.register_fn("num2",move || num2);
    let res = engine.eval_file::<i64>("src/add.rhai".into()).unwrap();
    format!("{res}")
}
#[actix_web::main]
async fn main()->std::io::Result<()> {
    HttpServer::new(|| {
        App::new() 
            // 注册服务
            .service(multiply)
            .service(add)
    })
    .bind(("127.0.0.1",8080))
    .unwrap()
    .run()
    .await
}

脚本

add.rhai (实现加法)

fn add(num1,num2){
    return num1 + num2;
}
let num1 = num1();
let num2 = num2();
add(num1,num2);

multiply.rhai (实现乘法)

fn multiply(num1,num2){
    return num1 * num2;
}
let num1 = num1();
let num2 = num2();
multiply(num1,num2);

运行结果

Logo

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!

更多推荐