Reimplement basic static (+handlebars) file hosting with actix-web

This commit is contained in:
Tristan Daniël Maat 2022-08-15 01:26:45 +01:00
parent 26ec66d03e
commit 0f736978f3
Signed by: tlater
GPG key ID: 49670FD774E43268
6 changed files with 601 additions and 2393 deletions

View file

@ -1,34 +1,46 @@
#![feature(proc_macro_hygiene, decl_macro)]
use std::io;
use rocket::fairing::AdHoc;
use actix_files::Files;
use actix_web::{web, App, HttpRequest, HttpResponse, HttpServer, Responder};
use clap::Parser;
use handlebars::Handlebars;
use rocket_contrib::serve::StaticFiles;
use rocket_contrib::templates::Template;
mod context;
mod mail;
mod static_templates;
use mail::routes as mail_routes;
use static_templates::routes as static_templates;
fn main() {
rocket::ignite()
.attach(Template::fairing())
.mount("/", mail_routes())
.mount("/", static_templates())
.attach(AdHoc::on_attach("Static files config", |rocket| {
let static_path = match rocket.config().get_string("template_dir") {
Ok(dir) => dir,
Err(rocket::config::ConfigError::Missing { .. }) => "templates".to_string(),
Err(err) => {
eprintln!("Error reading configuration: {}", err);
eprintln!("Using default templates path.");
"templates".to_string()
},
};
Ok(rocket.mount("/", StaticFiles::from(static_path)))
}))
.launch();
#[derive(Parser, Debug)]
struct Config {
template_directory: String,
address: String,
port: u16,
}
async fn template(hb: web::Data<Handlebars<'_>>, req: HttpRequest) -> impl Responder {
let path: String = req
.match_info()
.query("filename")
.parse()
.expect("need a file name on the request");
let body = hb.render(path.strip_suffix(".html").unwrap(), &()).unwrap();
HttpResponse::Ok().body(body)
}
#[actix_web::main]
async fn main() -> io::Result<()> {
let config = Config::parse();
let mut handlebars = Handlebars::new();
handlebars
.register_templates_directory(".html", config.template_directory.clone())
.expect("could not read template directory");
let handlebars_ref = web::Data::new(handlebars);
HttpServer::new(move || {
App::new()
.app_data(handlebars_ref.clone())
.route("/{filename:.*.html}", web::get().to(template))
.service(Files::new("/", config.template_directory.clone()))
})
.bind((config.address, config.port))?
.run()
.await
}