diff --git a/Cargo.lock b/Cargo.lock index 0a1504b..be981e3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -389,6 +389,7 @@ version = "0.1.0" dependencies = [ "anyhow", "async-std", + "html-escape", "rocket", "sqlx", ] @@ -952,6 +953,15 @@ dependencies = [ "windows-sys 0.52.0", ] +[[package]] +name = "html-escape" +version = "0.2.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d1ad449764d627e22bfd7cd5e8868264fc9236e07c752972b4080cd351cb476" +dependencies = [ + "utf8-width", +] + [[package]] name = "http" version = "0.2.12" @@ -2560,6 +2570,12 @@ version = "2.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "daf8dba3b7eb870caf1ddeed7bc9d2a049f3cfdfae7cb521b087cc33ae4c49da" +[[package]] +name = "utf8-width" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86bd8d4e895da8537e5315b8254664e6b769c4ff3db18321b297a1e7004392e3" + [[package]] name = "valuable" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 5718113..51e456a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -8,5 +8,6 @@ edition = "2021" [dependencies] anyhow = "1.0.82" async-std = { version = "1.12.0", features = ["attributes"] } +html-escape = "0.2.13" rocket = "0.5.0" sqlx = { version = "0.7", features = ["runtime-async-std", "sqlite", "migrate"] } diff --git a/src/main.rs b/src/main.rs index 1c93f9f..ed67119 100644 --- a/src/main.rs +++ b/src/main.rs @@ -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, sql } #[rocket::get("/txt?")] -async fn index(page: &str, pool: &rocket::State) -> Result { +async fn txt(page: &str, pool: &rocket::State) -> Result { 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) -> Result()) } +#[rocket::get("/html?")] +async fn html( + page: &str, + pool: &rocket::State, +) -> Result, String> { + let comments = get_comments(pool, page) + .await + .map_err(|_| "error fetching comments for this page, sorry")?; + + let html = format!( + r#"
{}
"#, + comments + .into_iter() + .map(|rec| { + format!( + r#" +
+
{}
+
{}
+
+ "#, + rec.id, + html_escape::encode_text(&rec.name.unwrap_or("anonymous".to_owned())), + html_escape::encode_text(&rec.content), + ) + }) + .collect::() + ); + + Ok(content::RawHtml(html)) +} + #[rocket::get("/add?&&")] 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]) }