Always cache media, use CacheControl header for statics

This commit is contained in:
asonix 2020-05-21 18:51:11 -05:00
parent fbebe412f3
commit 4b9a8c5354
2 changed files with 24 additions and 12 deletions

View file

@ -1,5 +1,9 @@
use crate::{data::Media, error::MyError, requests::Requests};
use actix_web::{web, HttpResponse};
use actix_web::{
http::header::{CacheControl, CacheDirective},
web, HttpResponse,
};
use bytes::Bytes;
use uuid::Uuid;
pub async fn route(
@ -10,7 +14,7 @@ pub async fn route(
let uuid = uuid.into_inner();
if let Some((content_type, bytes)) = media.get_bytes(uuid).await {
return Ok(HttpResponse::Ok().content_type(content_type).body(bytes));
return Ok(cached(content_type, bytes));
}
if let Some(url) = media.get_url(uuid).await? {
@ -20,11 +24,19 @@ pub async fn route(
.store_bytes(uuid, content_type.clone(), bytes.clone())
.await;
return Ok(HttpResponse::Ok()
.content_type(content_type)
.header("Cache-Control", "public, max-age=1200, immutable")
.body(bytes));
return Ok(cached(content_type, bytes));
}
Ok(HttpResponse::NotFound().finish())
}
fn cached(content_type: String, bytes: Bytes) -> HttpResponse {
HttpResponse::Ok()
.set(CacheControl(vec![
CacheDirective::Public,
CacheDirective::MaxAge(60 * 60 * 24),
CacheDirective::Extension("immutable".to_owned(), None),
]))
.content_type(content_type)
.body(bytes)
}

View file

@ -1,17 +1,17 @@
use crate::templates::statics::StaticFile;
use actix_web::{
http::header::{ContentType, Expires},
http::header::{CacheControl, CacheDirective, ContentType},
web, HttpResponse,
};
use std::time::{Duration, SystemTime};
static FAR: Duration = Duration::from_secs(60 * 60 * 24);
pub async fn route(filename: web::Path<String>) -> HttpResponse {
if let Some(data) = StaticFile::get(&filename.into_inner()) {
let far_expires = SystemTime::now() + FAR;
HttpResponse::Ok()
.set(Expires(far_expires.into()))
.set(CacheControl(vec![
CacheDirective::Public,
CacheDirective::MaxAge(60 * 60 * 24),
CacheDirective::Extension("immutable".to_owned(), None),
]))
.set(ContentType(data.mime.clone()))
.body(data.content)
} else {