Created
August 21, 2025 12:35
-
-
Save mcihad/90c4eef93573e043507a709f3472b283 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| use rocket::http::Status; | |
| use rocket::response::content::RawHtml; | |
| use rocket::tokio::time::{Duration, sleep}; | |
| #[macro_use] | |
| extern crate rocket; | |
| use std::collections::HashMap; | |
| #[get("/")] | |
| fn index() -> &'static str { | |
| "Hello, world!" | |
| } | |
| #[get("/delay/<seconds>")] | |
| async fn delay(seconds: u64) -> &'static str { | |
| sleep(Duration::from_secs(seconds)).await; | |
| "Delay complete" | |
| } | |
| #[get("/template/<name>")] | |
| async fn render_template(name: &str) -> Result<RawHtml<String>, (Status, String)> { | |
| // Build the file path by appending ".hbs" | |
| let filename = format!("templates/{}.hbs", name); | |
| // Read template source | |
| let tpl = std::fs::read_to_string(&filename).map_err(|e| { | |
| ( | |
| Status::NotFound, | |
| format!("Template '{}' not found: {}", filename, e), | |
| ) | |
| })?; | |
| // Register and render with Handlebars | |
| let mut hb = handlebars::Handlebars::new(); | |
| hb.register_template_string(name, tpl).map_err(|e| { | |
| ( | |
| Status::InternalServerError, | |
| format!("Template register error: {}", e), | |
| ) | |
| })?; | |
| let mut data: HashMap<String, String> = HashMap::new(); | |
| data.insert("name".to_string(), name.to_string()); | |
| let rendered = hb | |
| .render(name, &data) | |
| .map_err(|e| (Status::InternalServerError, format!("Render error: {}", e)))?; | |
| Ok(RawHtml(rendered)) | |
| } | |
| #[launch] | |
| fn rocket() -> _ { | |
| rocket::build().mount("/", routes![index, delay, render_template]) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment