grace/htmlua

HTML Templating Engine

git clone https://git.gae.moe/grace/htmlua

gyoderAdded Basic HTTP stdlib4144fa2

httpstdlib
4.6 KiB151 linesraw
1use std::{cell::{LazyCell, RefCell}, collections::HashMap, fmt::Write, rc::Rc};
2
3use anyhow::anyhow;
4use mlua::{prelude::*, Error, Lua, Table};
5use reqwest::{blocking::{Client, Response}, header::HeaderMap};
6use serde::{Deserialize, Serialize};
7use serde_json::to_value;
8
9
10pub fn create_htmlua_stdlib(l: &Lua, stdout: &Rc<RefCell<String>>) -> mlua::Result<Table> {
11    let t = l.create_table()?;
12
13    // This cannot be the best way to do this
14
15    let stdout_println = stdout.clone();
16    t.set(
17        "println",
18        l.create_function(move |_, text: String| {
19            let mut stdout_ref = stdout_println.borrow_mut();
20            writeln!(stdout_ref, "{text}").map_err(mlua::Error::external)
21        })?,
22    )?;
23
24    let stdout_print = stdout.clone();
25    t.set(
26        "print",
27        l.create_function(move |_, text: String| {
28            let mut stdout_ref = stdout_print.borrow_mut();
29            write!(stdout_ref, "{text}").map_err(mlua::Error::external)
30        })?,
31    )?;
32
33    t.set("http", create_http_lib(l)?)?;
34    Ok(t)
35}
36
37fn create_http_lib(l: &Lua) -> mlua::Result<Table> {
38    let t = l.create_table()?;
39    let http_client: Rc<LazyCell<Client>> = Rc::new(LazyCell::new(|| Client::builder()
40            .timeout(std::time::Duration::from_secs(3))
41            .user_agent("htmlua/0.1.0")
42            .build().unwrap()
43        ));
44
45
46    let client = http_client.clone();
47    t.set(
48        "get",
49        l.create_function(move |_, url: String| {
50            let res = client.get(url).send().map_err(|e| Error::RuntimeError(e.to_string()))?;
51            let lua_res: LuaHttpResponse = TryFrom::try_from(res)?;
52            Ok(lua_res)
53        })?
54    )?;
55
56    let client = http_client.clone();
57    t.set(
58        "post",
59        l.create_function(move |_, url: String| {
60            let res = client.post(url).send().map_err(|e| Error::RuntimeError(e.to_string()))?;
61            let lua_res: LuaHttpResponse = TryFrom::try_from(res)?;
62            Ok(lua_res)
63        })?
64    )?;
65
66    let client = http_client.clone();
67    t.set(
68        "get_with_data",
69        l.create_function(move |_, (url, data): (String, HashMap<String, String>)| {
70            let res = client.get(url).query(&data).send().map_err(|e| Error::RuntimeError(e.to_string()))?;
71            let lua_res: LuaHttpResponse = TryFrom::try_from(res)?;
72            Ok(lua_res)
73        })?
74    )?;
75
76    let client = http_client.clone();
77    t.set(
78        "post_with_data_form",
79        l.create_function(move |_, (url, data): (String, HashMap<String, String>)| {
80            let res = client.post(url).form(&data).send().map_err(|e| Error::RuntimeError(e.to_string()))?;
81            let lua_res: LuaHttpResponse = TryFrom::try_from(res)?;
82            Ok(lua_res)
83        })?
84    )?;
85
86    let client = http_client.clone();
87    t.set(
88        "post_with_data_json",
89        l.create_function(move |_, (url, data): (String, HashMap<String, String>)| {
90            let res = client.post(url).json(&data).send().map_err(|e| Error::RuntimeError(e.to_string()))?;
91            let lua_res: LuaHttpResponse = TryFrom::try_from(res)?;
92            Ok(lua_res)
93        })?
94    )?;
95    //TODO: all http
96
97    t.set(
98        "decode_json",
99        l.create_function(move |l, text: String| {
100            let table: serde_json::Value = serde_json::from_str(&text).map_err(|e| Error::RuntimeError(e.to_string()))?;
101            Ok(l.to_value(&table))
102        })?
103    )?;
104
105    Ok(t)
106}
107
108
109#[derive(Serialize, Deserialize)]
110struct LuaHttpResponse {
111    headers: HashMap<String, String>,
112    body: String,
113    status: u16,
114}
115
116impl TryFrom<Response> for LuaHttpResponse {
117    fn try_from(value: Response) -> Result<Self, Self::Error> {
118        Ok(LuaHttpResponse { headers: headermap_to_hashmap(value.headers()), status: value.status().as_u16(), body: value.text().map_err(|e| Error::RuntimeError(e.to_string()))?, })
119    }
120
121    type Error = Error;
122}
123
124fn headermap_to_hashmap(headers: &HeaderMap) -> HashMap<String, String> {
125    let mut map = HashMap::new();
126
127    for (name, value) in headers {
128        if let Ok(value_str) = value.to_str() {
129            map.insert(name.as_str().to_string(), value_str.to_string());
130        }
131    }
132
133    map
134}
135
136impl IntoLua for LuaHttpResponse {
137    fn into_lua(self, lua: &Lua) -> LuaResult<LuaValue> {
138        let table = lua.create_table()?;
139
140        table.set("status", self.status)?;
141        table.set("body", self.body)?;
142
143        let headers_table = lua.create_table()?;
144        for (key, value) in self.headers {
145            headers_table.set(key, value)?;
146        }
147        table.set("headers", headers_table)?;
148
149        Ok(LuaValue::Table(table))
150    }
151}