hyaenidae/toolkit-examples/src/main.rs
2021-01-07 22:45:21 -06:00

60 lines
1.4 KiB
Rust

use actix_web::{
middleware::{Compress, Logger},
web, App, HttpResponse, HttpServer,
};
use std::io::Cursor;
include!(concat!(env!("OUT_DIR"), "/templates.rs"));
#[actix_web::main]
async fn main() -> anyhow::Result<()> {
if std::env::var("RUST_LOG").is_err() {
std::env::set_var("RUST_LOG", "info");
}
env_logger::init();
HttpServer::new(move || {
App::new()
.wrap(Logger::default())
.wrap(Compress::default())
.route("/", web::get().to(index))
})
.bind("0.0.0.0:8083")?
.run()
.await?;
Ok(())
}
async fn index() -> HttpResponse {
match try_index().await {
Ok(res) => res,
Err(e) => HttpResponse::InternalServerError()
.content_type(mime::TEXT_PLAIN.essence_str())
.body(e.to_string()),
}
}
async fn try_index() -> anyhow::Result<HttpResponse> {
rendered(|cursor| self::templates::index(cursor))
}
fn rendered(
f: impl FnOnce(&mut Cursor<&mut Vec<u8>>) -> std::io::Result<()>,
) -> anyhow::Result<HttpResponse> {
let mut bytes = vec![];
(f)(&mut Cursor::new(&mut bytes))?;
minify_html::truncate(
&mut bytes,
&minify_html::Cfg {
minify_js: false,
minify_css: false,
},
)
.map_err(|_| anyhow::anyhow!("Truncate error"))?;
Ok(HttpResponse::Ok()
.content_type(mime::TEXT_HTML.essence_str())
.body(bytes))
}