use std::path::PathBuf;
use axum::Router;
use axum::extract::DefaultBodyLimit;
use axum::http::{HeaderValue, header};
use tower::ServiceBuilder;
use tower_http::services::ServeDir;
use tower_http::set_header::SetResponseHeaderLayer;
pub const PROTECTED_API_BODY_LIMIT_BYTES: usize = 220 * 1024 * 1024;
pub fn layer_protected_body_limit<S>(router: Router<S>) -> Router<S>
where
S: Clone + Send + Sync + 'static,
{
router.layer(DefaultBodyLimit::max(PROTECTED_API_BODY_LIMIT_BYTES))
}
pub fn mount_uploads_and_spa<S>(
mut app: Router<S>,
uploads_dir: PathBuf,
static_dir: Option<PathBuf>,
allow_cross_origin_uploads: bool,
) -> Router<S>
where
S: Clone + Send + Sync + 'static,
{
let corp = if allow_cross_origin_uploads {
HeaderValue::from_static("cross-origin")
} else {
HeaderValue::from_static("same-site")
};
app = app.nest_service(
"/uploads",
ServiceBuilder::new()
.layer(SetResponseHeaderLayer::if_not_present(
header::CACHE_CONTROL,
HeaderValue::from_static("public, max-age=31536000, immutable"),
))
.layer(SetResponseHeaderLayer::if_not_present(
header::X_CONTENT_TYPE_OPTIONS,
HeaderValue::from_static("nosniff"),
))
.layer(SetResponseHeaderLayer::if_not_present(
header::HeaderName::from_static("cross-origin-resource-policy"),
corp,
))
.service(ServeDir::new(uploads_dir)),
);
if let Some(dir) = static_dir {
app = app.fallback_service(ServeDir::new(dir));
}
app
}