use std::{
convert::Infallible,
sync::Arc,
task::{Context, Poll},
};
use axum::{
Router,
body::Body,
http::{Request, StatusCode, header},
response::{IntoResponse, Response},
};
use futures_util::future::BoxFuture;
use mlua::{UserData as LuaUserData, UserDataMethods as LuaUserDataMethods};
use tower;
#[derive(Clone)]
struct Uri
{
wrapped: axum::http::Uri,
}
impl LuaUserData for Uri
{
fn add_methods<M: LuaUserDataMethods<Self>>(methods: &mut M)
{
methods.add_method("to_string", |_, uri: &Uri, ()| Ok(uri.wrapped.to_string()));
}
}
pub struct Binder {}
impl inyanga::Binder for Binder
{
fn get_lua_bindings(
&self,
uri: &axum::http::Uri,
_request_body: &Body,
_is_post: bool,
) -> inyanga::parser::InsideScopeHook
{
let uri = uri.clone();
Some(Box::new(move |lua, _scope| {
let globals = lua.globals();
globals.set("SERVER_NAME", "Inyanga Example").unwrap();
globals.set("URI", Uri { wrapped: uri }).unwrap();
let printer = lua
.create_function(|_, text: String| {
println!("Printed from lua: {}", text);
Ok(())
})
.unwrap();
globals.set("rust_callback_that_prints", printer).unwrap();
}))
}
}
#[derive(Clone)]
pub struct Service {}
impl tower::Service<Request<Body>> for Service
{
type Response = Response;
type Error = Infallible;
type Future = BoxFuture<'static, Result<Self::Response, Self::Error>>;
fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>>
{
Poll::Ready(Ok(()))
}
fn call(&mut self, _request: Request<Body>) -> Self::Future
{
Box::pin(async move {
let response = (
StatusCode::OK,
[(header::CONTENT_TYPE, "text/html")],
"<!DOCTYPE html>
<html>
<head>
<style>
span {
font-family: monospace;
background-color: black;
color: lightgrey;
}
</style>
</head>
<body>
<h1>INYANGA</h1>
<?lua local uri = URI:to_string() ?>
<h2>Example page</h2>
<h3>Evaluate an expression in Lua including a local variable:</h3>
<p><span><?lua echo(uri) ?></span> is interpreted as <?lua echo(uri) ?></p>
<h3>Evaluate a statement in Lua:</h3>
<p><span><?= 2 + 2 ?></span> is interpreted as <?= 2 + 2 ?></p>
<h3>Evaluate a loop</h3>
<?lua
for i = 1, 5 do
?><p><?lua echo('Number: ' .. i)?><p><?lua
end
?>
<h3>Call a Rust callback from Lua:</h3>
<p>
<span><?lua rust_callback_that_prints(uri .. ' ' .. SERVER_NAME) ?></span>
<em>Check the server console for output</em>
</p>
<?lua rust_callback_that_prints(uri .. ' ' .. SERVER_NAME) ?>
</body>
</html>"
.to_string(),
)
.into_response();
Ok(response)
})
}
}
#[tokio::main]
async fn main()
{
let app = make_router();
let listener = tokio::net::TcpListener::bind("127.0.0.1:8080")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
fn make_router() -> Router
{
let service = Service {};
let lua_binder = Arc::new(Binder {});
Router::new()
.fallback_service(service)
.layer(inyanga::Layer {
binder: Some(lua_binder.clone()),
})
}