Add `reqwest` http client example to fetch json

This commit is contained in:
Alex Orlenko 2020-12-28 01:10:47 +00:00
parent ce8955f5b9
commit c5d0ccc433
3 changed files with 48 additions and 2 deletions

View File

@ -59,11 +59,12 @@ lua-src = { version = ">= 540.0.0, < 550.0.0", optional = true }
luajit-src = { version = ">= 210.1.0, < 220.0.0", optional = true }
[dev-dependencies]
rustyline = "6.0"
rustyline = "7.0"
criterion = "0.3"
trybuild = "1.0"
futures = "0.3.5"
hyper = "0.13"
reqwest = { version = "0.10", features = ["json"] }
tokio = { version = "0.2", features = ["full"] }
futures-timer = "3.0"
serde_json = "1.0"
@ -76,6 +77,10 @@ harness = false
name = "async_http_client"
required-features = ["async"]
[[example]]
name = "async_http_reqwest"
required-features = ["async", "serialize"]
[[example]]
name = "async_http_server"
required-features = ["async", "send"]

View File

@ -0,0 +1,41 @@
use mlua::{Error, Lua, LuaSerdeExt, Result};
#[tokio::main]
async fn main() -> Result<()> {
let lua = Lua::new();
let globals = lua.globals();
globals.set("null", lua.null()?)?;
let fetch_json = lua.create_async_function(|lua, uri: String| async move {
let resp = reqwest::get(&uri)
.await
.and_then(|resp| resp.error_for_status())
.map_err(Error::external)?;
let json = resp
.json::<serde_json::Value>()
.await
.map_err(Error::external)?;
lua.to_value(&json)
})?;
globals.set("fetch_json", fetch_json)?;
let f = lua
.load(
r#"
function print_r(t, indent)
local indent = indent or ''
for k, v in pairs(t) do
io.write(indent, tostring(k))
if type(v) == "table" then io.write(':\n') print_r(v, indent..' ')
else io.write(': ', v == null and "null" or tostring(v), '\n') end
end
end
local res = fetch_json(...)
print_r(res)
"#,
)
.into_function()?;
f.call_async("https://httpbin.org/anything?arg0=val0").await
}

View File

@ -2,8 +2,8 @@ use std::net::Shutdown;
use std::sync::Arc;
use bstr::BString;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{TcpListener, TcpStream};
use tokio::prelude::*;
use tokio::sync::Mutex;
use tokio::task;