extern crate tela;
use serde::{Deserialize, Serialize};
use tela::{
prelude::*,
request::{Body, Query},
response::{HTML, JSON},
Server,
};
#[get("/api/:firstname/:lastname/from/:...path")]
pub fn uri_capture(
firstname: String,
lastname: Option<String>,
path: Result<String>,
) -> HTML<String> {
html! {
<h1>{firstname}" "{lastname.unwrap_or("<None>".to_string())}": "<code>{path.unwrap()}</code></h1>
}
}
#[get("/api/query")]
pub fn query(Query(q): Query<String>) -> HTML<String> {
html! {
<h4>"Query: "{ q }</h4>
}
}
#[derive(Deserialize, Serialize, Default)]
struct UserQuery {
name: String,
}
#[get("/api/optional-query")]
pub fn optional_query(q: Result<Query<UserQuery>>) -> Result<JSON<UserQuery>> {
q.map(|Query(q)| response!(JSON(q)))?
}
#[post("/api/body")]
pub fn _body(Body(b): Body<String>) -> HTML<String> {
html! {
<h4>"Body"</h4>
<pre>{b}</pre>
}
}
#[post("/api/optional-body")]
pub fn optional_body(b: Result<Body<u32>>) -> Result<HTML<String>> {
b.map(|Body(num)| {
html! {
<h4>"Body"</h4>
<pre>{num}</pre>
}
})
}
#[get("/")]
fn home() -> HTML<String> {
html! {
<script>
"
function body_request() {
fetch(
'http://localhost:3000/api/body',
{ method: 'POST', body: 'Hello, world!' }
)
.then(async response => {
const result = document.getElementById('result');
if (result) {
let text = await response.text();
result.innerHTML = text;
}
})
.catch(reason => console.error(reason));
}
function optional_body_request() {
fetch(
'http://localhost:3000/api/optional-body',
{ method: 'POST', body: 32 }
)
.then(async response => {
const result = document.getElementById('result');
if (result) {
let text = await response.text();
result.innerHTML = text;
}
})
.catch(reason => console.error(reason));
}
"
</script>
<button onclick="body_request()">"Body Request"</button>
<button onclick="optional_body_request()">"Optional Body Request"</button>
<div id="result"></div>
}
}
#[tela::main]
async fn main() {
Server::new()
.route(home)
.route(uri_capture)
.routes(group![query, optional_query])
.routes(group![_body, optional_body])
.serve(3000)
.await
}