-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathasync_request.rs
50 lines (42 loc) · 1.3 KB
/
async_request.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
use std::panic::AssertUnwindSafe;
use futures_util::FutureExt;
use hebi::prelude::*;
#[tokio::main]
async fn main() {
let client = reqwest::Client::default();
async fn get(scope: Scope<'_>, client: reqwest::Client) -> hebi::Result<Str<'_>> {
let url = scope.param::<Str>(0)?;
let request = client.get(url.as_str());
let response = request.send().await.map_err(hebi::Error::user)?;
let bytes = response.bytes().await.map_err(hebi::Error::user)?.to_vec();
let str = String::from_utf8(bytes).map_err(hebi::Error::user)?;
Ok(scope.new_string(str))
}
let module = NativeModule::builder("http")
.async_function("get", move |scope| get(scope, client.clone()))
.finish();
let mut hebi = Hebi::new();
hebi.register(&module);
let source = r#"
from http import get
get("https://jsonplaceholder.typicode.com/todos/1")
"#;
let result = AssertUnwindSafe(hebi.eval_async(source))
.catch_unwind()
.await;
match result {
Ok(result) => match result {
Ok(value) => println!("Result is:\n{value}"),
Err(e) => {
eprintln!("{}", e.report(source, true))
}
},
Err(panic) => {
println!("hebi panicked");
for (key, value) in hebi.global().entries() {
println!("{key}: {value}")
}
std::panic::panic_any(panic)
}
}
}