问题描述
我想用 cargo-wasi 编译以下代码。
// reqwest = { version = "0.11",features = ["json"] }
// tokio = { version = "1",features = ["full"] }
use std::collections::HashMap;
#[tokio::main]
async fn main() -> Result<(),Box<dyn std::error::Error>> {
let resp = reqwest::get("https://httpbin.org/ip")
.await?
.json::<HashMap<String,String>>()
.await?;
println!("{:#?}",resp);
Ok(())
}
尝试编译后,我收到以下错误,因为 mio doesn't currently support WASI
$ cargo wasi run
Compiling mio v0.7.9
Compiling parking_lot v0.11.1
Compiling serde_json v1.0.64
Compiling idna v0.2.2
error[E0432]: unresolved import `crate::sys::IoSourceState`
--> /home/ducaale/.cargo/registry/src/github.com-1ecc6299db9ec823/mio-0.7.9/src/io_source.rs:12:5
|
12 | use crate::sys::IoSourceState;
| ^^^^^^^^^^^^^^^^^^^^^^^^^ no `IoSourceState` in `sys`
... errors omitted
我做了一些研究,到目前为止我发现的 examples 都没有使用 async/await。有什么可以替换 tokio
以便我的代码在 WASI 中编译的吗?
解决方法
我尝试运行它,但似乎 reqwests crate 无法使用 Cargo wasi 或 wasm-pack 正确构建,因为它无法编译 mio(在本地编译时由 tokio 使用)。在 github 上有一些提到 reqwests 可以与 wasm 一起使用,但它还没有得到完全支持,我找不到太多关于如何使其工作的信息。 WASI 上的 HTTP 请求目前似乎还没有太多解决方案,但是 web-sys 可以用于通过 Node.js 或浏览器发出请求。
似乎 tokio 需要特定功能标志才能与 Web 程序集一起使用。这个问题在底部提到了同步和 rt 标志:https://github.com/tokio-rs/tokio/issues/1597 但为了也使用 #[tokio:main],您还需要“rt-multi-thread”和“macros”功能标志。
也可以使用 wasm bindgen 将未来转换为承诺,但这可能不适用于 WASI:https://rustwasm.github.io/wasm-bindgen/api/wasm_bindgen_futures/