First implementation with mime_guess

This commit is contained in:
clowzed 2023-11-16 14:20:40 +03:00
parent 966f8a6abf
commit 457589e8bf
2 changed files with 23 additions and 15 deletions

View file

@ -44,6 +44,7 @@ reqwest = { version = "0.11.22", features = ["json", "multipart"] }
oneshot = "0.1.6" oneshot = "0.1.6"
crossfire = "1.0.1" crossfire = "1.0.1"
http-body = "0.4.5" http-body = "0.4.5"
mime_guess = "2.0.4"
[workspace] [workspace]
members = [".", "entity", "migration"] members = [".", "entity", "migration"]

View file

@ -13,7 +13,10 @@ use sea_orm::prelude::*;
use axum::{ use axum::{
body::StreamBody, body::StreamBody,
extract::{Path, State}, extract::{Path, State},
http::StatusCode, http::{
header::{self, HeaderMap},
StatusCode,
},
response::{IntoResponse, Response}, response::{IntoResponse, Response},
}; };
@ -114,7 +117,7 @@ pub async fn index_redirect(
pub async fn file( pub async fn file(
State(state): State<Arc<AppState>>, State(state): State<Arc<AppState>>,
SubdomainModelExtractor(subdomain): SubdomainModelExtractor, SubdomainModelExtractor(subdomain): SubdomainModelExtractor,
Path(mut path): Path<String>, Path(path): Path<String>,
) -> Response { ) -> Response {
if !subdomain.enabled { if !subdomain.enabled {
return match SitesService::getfile(&subdomain, "503.html".to_owned(), &state.connection) return match SitesService::getfile(&subdomain, "503.html".to_owned(), &state.connection)
@ -132,20 +135,24 @@ pub async fn file(
}; };
} }
if path.is_empty() {
path = "index.html".to_owned();
}
match SitesService::getfile(&subdomain, path, &state.connection).await { match SitesService::getfile(&subdomain, path, &state.connection).await {
Ok(Some((is_404, file))) => ( Ok(Some((is_404, file))) => {
match is_404 { let mut headers = HeaderMap::new();
true => StatusCode::NOT_FOUND, if let Some(mime_type) = mime_guess::from_path(&file).first() {
false => StatusCode::OK, headers.insert(header::CONTENT_TYPE, mime_type.to_string().parse().unwrap());
}, }
StreamBody::new(ReaderStream::new( (
tokio::fs::File::open(file).await.unwrap(), match is_404 {
)), true => StatusCode::NOT_FOUND,
) false => StatusCode::OK,
.into_response(), },
headers,
StreamBody::new(ReaderStream::new(
tokio::fs::File::open(file).await.unwrap(),
)),
)
.into_response()
}
Ok(None) => StatusCode::NOT_FOUND.into_response(), Ok(None) => StatusCode::NOT_FOUND.into_response(),
Err(cause) => SeroError::InternalServerError(Box::new(cause)).into_response(), Err(cause) => SeroError::InternalServerError(Box::new(cause)).into_response(),
} }