Skip to content

Commit c5d0ccc

Browse files
committed
Add reqwest http client example to fetch json
1 parent ce8955f commit c5d0ccc

File tree

3 files changed

+48
-2
lines changed

3 files changed

+48
-2
lines changed

Cargo.toml

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,11 +59,12 @@ lua-src = { version = ">= 540.0.0, < 550.0.0", optional = true }
5959
luajit-src = { version = ">= 210.1.0, < 220.0.0", optional = true }
6060

6161
[dev-dependencies]
62-
rustyline = "6.0"
62+
rustyline = "7.0"
6363
criterion = "0.3"
6464
trybuild = "1.0"
6565
futures = "0.3.5"
6666
hyper = "0.13"
67+
reqwest = { version = "0.10", features = ["json"] }
6768
tokio = { version = "0.2", features = ["full"] }
6869
futures-timer = "3.0"
6970
serde_json = "1.0"
@@ -76,6 +77,10 @@ harness = false
7677
name = "async_http_client"
7778
required-features = ["async"]
7879

80+
[[example]]
81+
name = "async_http_reqwest"
82+
required-features = ["async", "serialize"]
83+
7984
[[example]]
8085
name = "async_http_server"
8186
required-features = ["async", "send"]

examples/async_http_reqwest.rs

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
use mlua::{Error, Lua, LuaSerdeExt, Result};
2+
3+
#[tokio::main]
4+
async fn main() -> Result<()> {
5+
let lua = Lua::new();
6+
let globals = lua.globals();
7+
globals.set("null", lua.null()?)?;
8+
9+
let fetch_json = lua.create_async_function(|lua, uri: String| async move {
10+
let resp = reqwest::get(&uri)
11+
.await
12+
.and_then(|resp| resp.error_for_status())
13+
.map_err(Error::external)?;
14+
let json = resp
15+
.json::<serde_json::Value>()
16+
.await
17+
.map_err(Error::external)?;
18+
lua.to_value(&json)
19+
})?;
20+
globals.set("fetch_json", fetch_json)?;
21+
22+
let f = lua
23+
.load(
24+
r#"
25+
function print_r(t, indent)
26+
local indent = indent or ''
27+
for k, v in pairs(t) do
28+
io.write(indent, tostring(k))
29+
if type(v) == "table" then io.write(':\n') print_r(v, indent..' ')
30+
else io.write(': ', v == null and "null" or tostring(v), '\n') end
31+
end
32+
end
33+
34+
local res = fetch_json(...)
35+
print_r(res)
36+
"#,
37+
)
38+
.into_function()?;
39+
40+
f.call_async("https://httpbin.org/anything?arg0=val0").await
41+
}

examples/async_tcp_server.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,8 @@ use std::net::Shutdown;
22
use std::sync::Arc;
33

44
use bstr::BString;
5+
use tokio::io::{AsyncReadExt, AsyncWriteExt};
56
use tokio::net::{TcpListener, TcpStream};
6-
use tokio::prelude::*;
77
use tokio::sync::Mutex;
88
use tokio::task;
99

0 commit comments

Comments
 (0)