| 1 | use rust_embed::RustEmbed; |
| 2 | |
| 3 | use crate::prelude::*; |
| 4 | |
| 5 | #[derive(RustEmbed)] |
| 6 | #[folder = "static/"] |
| 7 | struct Static; |
| 8 | |
| 9 | #[get("/static/{filename:.*}")] |
| 10 | pub async fn files(req: HttpRequest, path: web::Path<String>) -> ActixResult<HttpResponse> { |
| 11 | let path = path.into_inner(); |
| 12 | |
| 13 | if path.is_empty() { |
| 14 | return Ok(HttpResponse::NotFound().body("Not Found")); |
| 15 | } |
| 16 | |
| 17 | match Static::get(&path) { |
| 18 | Some(content) => { |
| 19 | let hash = content.metadata.sha256_hash(); |
| 20 | let etag = format!( |
| 21 | "\"{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}\"", |
| 22 | hash[0], hash[1], hash[2], hash[3], hash[4], hash[5], hash[6], hash[7] |
| 23 | ); |
| 24 | |
| 25 | if let Some(if_none_match) = req.headers().get("If-None-Match") |
| 26 | && if_none_match.to_str().ok() == Some(&etag) |
| 27 | { |
| 28 | return Ok(HttpResponse::NotModified() |
| 29 | .insert_header(("ETag", etag)) |
| 30 | .finish()); |
| 31 | } |
| 32 | |
| 33 | let mime_type = mime_guess::from_path(&path).first_or_octet_stream(); |
| 34 | Ok(HttpResponse::Ok() |
| 35 | .content_type(mime_type.as_ref()) |
| 36 | .insert_header(("ETag", etag)) |
| 37 | .insert_header(("Cache-Control", "public, max-age=3600, must-revalidate")) |
| 38 | .body(content.data)) |
| 39 | } |
| 40 | None => Ok(HttpResponse::NotFound().body("Not Found")), |
| 41 | } |
| 42 | } |
