okay holy shit i can actually put HTML in responses now

This commit is contained in:
Erin 2024-04-15 03:25:50 -04:00
parent ac593e2882
commit 14d2792bed
Signed by: erin
SSH key fingerprint: SHA256:clvLPaxKthBet+VUQTKQdDkjaqg2/KnYHQaPASp5pFE
3 changed files with 52 additions and 2 deletions

View file

@ -1,3 +1,4 @@
use rocket::response::content;
use sqlx::SqlitePool;
use std::env;
@ -25,7 +26,7 @@ async fn get_comments(pool: &SqlitePool, page: &str) -> Result<Vec<Comment>, sql
}
#[rocket::get("/txt?<page>")]
async fn index(page: &str, pool: &rocket::State<SqlitePool>) -> Result<String, String> {
async fn txt(page: &str, pool: &rocket::State<SqlitePool>) -> Result<String, String> {
Ok(get_comments(pool, page)
.await
.map_err(|_| "error fetching comments for this page, sorry")?
@ -41,6 +42,38 @@ async fn index(page: &str, pool: &rocket::State<SqlitePool>) -> Result<String, S
.collect::<String>())
}
#[rocket::get("/html?<page>")]
async fn html(
page: &str,
pool: &rocket::State<SqlitePool>,
) -> Result<content::RawHtml<String>, String> {
let comments = get_comments(pool, page)
.await
.map_err(|_| "error fetching comments for this page, sorry")?;
let html = format!(
r#"<div class="comments">{}</div>"#,
comments
.into_iter()
.map(|rec| {
format!(
r#"
<div class="comment" data-id="{}">
<div class="comment__author">{}</div>
<div class="comment__content">{}</div>
</div>
"#,
rec.id,
html_escape::encode_text(&rec.name.unwrap_or("anonymous".to_owned())),
html_escape::encode_text(&rec.content),
)
})
.collect::<String>()
);
Ok(content::RawHtml(html))
}
#[rocket::get("/add?<page>&<name>&<content>")]
async fn add(
page: &str,
@ -69,5 +102,5 @@ async fn rocket() -> _ {
.expect("Failed to connect to database");
rocket::build()
.manage(pool)
.mount("/", rocket::routes![index, add])
.mount("/", rocket::routes![txt, html, add])
}