Actix-webでWASMを利用してみます。
テキストボックスに数値を入力し、ボタンを押すと+1した結果をラベルに記載する、というプログラムを作成してみます。
最初にWASMプロジェクトを作成します。
プロジェクト名を「wasm1」とします。
cargo generate --git https://github.com/rustwasm/wasm-pack-template
Project Name: wasm1
cd wasm1
Cargo.tomlファイルは下記のとおりに作成されます。
wasm1/Cargo.toml
[lib]
crate-type = ["cdylib", "rlib"]
[features]
default = ["console_error_panic_hook"]
[dependencies]
wasm-bindgen = "0.2.84"
console_error_panic_hook = { version = "0.1.7", optional = true }
[dev-dependencies]
wasm-bindgen-test = "0.3.34"
[profile.release]
# Tell `rustc` to optimize for small code size.
opt-level = "s"
lib.rsファイルの内容をプラス1する内容に書き換えます。
wasm1/src/lib.rs
mod utils;
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
pub fn plus1(x: i32) -> i32 {
x+1
}
WASMプロジェクトをビルドします。
wasm-pack build
別フォルダにWebプロジェクト(webapp1)を作成します。
cd ..
cargo new webapp1
cd webapp1
Cargo.tomlファイルのdependenciesに依存関係を追加します。
webapp1/Cargo.toml
[dependencies]
actix-web = "4.0"
actix-files = "0.6"
main.rsファイルにWebサーバーを設定する為、書き換えます。
use actix_files::Files;
use actix_web::{App, HttpServer, web, HttpResponse};
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
App::new()
.service(Files::new("/", "./static").index_file("index.html"))
})
.bind("0.0.0.0:8080")?
.run()
.await
}
ホームページ(index.html)ファイルを作成します。
mkdir static
cd static
touch index.html
webapp1/static/index.html
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Actix Web with WASM</title>
</head>
<body>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<input type='text' name='textbox1' value='0'><label> + 1</label><button id='button1' >=</button><label id='label1'>1</label>
<script type='text/javascript'>
$(window).on('load', function()
{
$('#button1').click(function()
{
const wasm = '/wasm1_bg.wasm'
fetch(wasm)
.then(response => response.arrayBuffer())
.then(bytes => WebAssembly.instantiate(bytes, {}))
.then(results =>
{
var num1 = Number($('input[name="textbox1"]').val());
$('#label1').text(results.instance.exports.plus1(num1));
})
});
});
</script>
</body>
</html>
wasm1プロジェクトでコンパイル後に作成された「wasm1_bg.wasm」ファイルを
webapp1プロジェクトのstaticフォルダ下にコピーします。
cd ../../wasm1/pkg
cp -r ./wasm1_bg.wasm ../../webapp1/static/
webapp1プロジェクトに戻ってコンパイル&実行します
cd ../../webapp1
cargo build
cargo run
localhost:8080/
にアクセスして、テキスボックスに数値を入力し、ボタンを押すと、+1した結果をラベルに表示します。
環境
ホストPC:Windows10
VirtualBox:ArchLinux
cargo:cargo 1.78.0 (54d8815d0 2024-03-26)
rustup:rustup 1.27.1 (54dd3d00f 2024-04-24)
wasm-pack:wasm-pack 0.12.1
以上