[web] Serve static assets

This commit is contained in:
Emi Simpson 2021-10-26 16:23:11 -04:00
parent 9176a5a0b8
commit cc4f3669c5
Signed by: Emi
GPG Key ID: A12F2C2FFDC3D847
2 changed files with 25 additions and 15 deletions

View File

@ -149,6 +149,9 @@ async fn main() -> std::io::Result<()> {
.wrap(middleware::NormalizePath::new(TrailingSlash::Trim))
.service(create_link);
let app = statics::STATIC_ASSETS.iter()
.fold(app, |app, asset| app.service(asset.generate_resource()));
#[cfg(feature = "ogp_images")]
let app = app
.service(resource("/thumb.png") .to(handle_thumbnail_request))

View File

@ -27,22 +27,23 @@ impl StaticAsset {
/// validated against the crate version after that.
pub fn generate_resource(&self) -> Resource {
let bytes = self.bytes;
resource(self.filename).to(move|req: HttpRequest| async move {
let mut response = HttpResponse::Ok();
response
.header("Etag", env!("CARGO_PKG_VERSION"))
.header("Cache-Control", "max-age=86400");
resource(format!("/static/{}", self.filename))
.to(move|req: HttpRequest| async move {
let mut response = HttpResponse::Ok();
response
.header("Etag", env!("CARGO_PKG_VERSION"))
.header("Cache-Control", "max-age=86400");
let req_etag = req.headers().get("If-None-Match");
match req_etag {
Some(etag) if etag == env!("CARGO_PKG_VERSION") => {
response.status(StatusCode::from_u16(304).unwrap()).finish()
let req_etag = req.headers().get("If-None-Match");
match req_etag {
Some(etag) if etag == env!("CARGO_PKG_VERSION") => {
response.status(StatusCode::from_u16(304).unwrap()).finish()
}
_ => {
response.body(bytes)
}
}
_ => {
response.body(bytes)
}
}
})
})
}
}
@ -52,7 +53,7 @@ impl StaticAsset {
macro_rules! static_asset {
( $filename: expr ) => {
StaticAsset {
filename: concat!("../assets/", $filename),
filename: $filename,
bytes: include_bytes!(concat!("../assets/", $filename)),
}
}
@ -61,3 +62,9 @@ macro_rules! static_asset {
/// The decorative font to be used for pronouns displayed at a very large size
#[cfg(any(feature = "embed_static_assets", feature = "ogp_images"))]
pub const FONT: StaticAsset = static_asset!("font.otf");
/// A list of static assets which should be served by the server
pub const STATIC_ASSETS: &[StaticAsset] = &[
#[cfg(any(feature = "embed_static_assets"))]
FONT,
];