In this project, we demonstrate how to use reqwest and tokio to build async http client in WebAssembly and execute it using WasmEdge.
There are growing demands to perform network requests in WASM and cloud computing. But it would be inefficient to perform network requests synchronously so we need async in WASM.
As tokio is widely accepted, we can bring many projects that depend on tokio to WASM if we can port tokio into WASM. After that, the developers can have async functions in WASM as well as efficient programs.
With the help of tokio support of WasmEdge, the developers can compile the projects that use tokio into WASM and execute it using WasmEdge.
We need install rust and wasm target first.
# install rust
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
# install wasm target
rustup target add wasm32-wasi
Then install the WasmEdge.
curl -sSf https://raw.githubusercontent.com/WasmEdge/WasmEdge/master/utils/install.sh | bash
In this project, we add tokio and reqwest as dependencies.
[dependencies]
reqwest = {git = "https://github.com/MediosZ/reqwest.git", branch = "wasmedge"}
tokio = { git="https://github.com/WasmEdge/tokio.git", branch = "wasmedge", features=["rt", "macros", "net", "time"]}
We need to add some code into src/main.rs
.
First we need to compile the code.
cargo build --target wasm32-wasi
Then we can run it using WasmEdge.
wasmedge target/wasm32-wasi/debug/wasmedge_reqwest_demo.wasm
For simpilicity, we can add the following configs to .cargo/config.toml
.
[build]
target="wasm32-wasi"
[target.wasm32-wasi]
runner = "wasmedge"
And then we can use cargo run
to execute it directly.
If you are using rustc 1.64, you may encounter this error. There are two options:
- Update rustc to newer version. Validated versions are
1.65
and1.59
. - Add
#![feature(wasi_ext)]
to the top ofmio/src/lib.rs
.