Skip to content

Commit

Permalink
Reworked serving of static files
Browse files Browse the repository at this point in the history
Amended the logic involved in serving static files, so that they will
only be streamed if loaded from the local filesystem.

This also fixes an issue where some baked-in static files were not being
served.
  • Loading branch information
danwilliams committed Jun 19, 2023
1 parent f643e24 commit 801dcda
Showing 1 changed file with 26 additions and 32 deletions.
58 changes: 26 additions & 32 deletions src/handlers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -180,42 +180,36 @@ async fn get_static_asset(
LoadingBehavior::Supplement => basedir.get_file(path).is_none(),
LoadingBehavior::Override => local_path.exists(),
};
let file = if is_local {
if local_path.exists() {
File::open(local_path).await.ok()
if !(
( is_local && local_path.exists())
|| (!is_local && basedir.get_file(path).is_some())
) {
return Err((StatusCode::NOT_FOUND, ""));
}
let body = if is_local {
let mut file = File::open(local_path).await.ok().unwrap();
let config = &state.Config.static_files;
if file.metadata().await.unwrap().len() as usize > 1024 * config.stream_threshold {
let reader = BufReader::with_capacity(1024 * config.read_buffer, file);
let stream = ReaderStream::with_capacity(reader, 1024 * config.stream_buffer);
Body::wrap_stream(stream)
} else {
None
let mut contents = vec![];
file.read_to_end(&mut contents).await.unwrap();
Body::from(contents)
}
} else {
match basedir.get_file(path) {
Some(file) => File::open(file.path()).await.ok(),
None => None,
}
Body::from(basedir.get_file(path).unwrap().contents())
};
match file {
None => Err((StatusCode::NOT_FOUND, "")),
Some(mut file) => {
let config = &state.Config.static_files;
let body = if file.metadata().await.unwrap().len() as usize > 1024 * config.stream_threshold {
let reader = BufReader::with_capacity(1024 * config.read_buffer, file);
let stream = ReaderStream::with_capacity(reader, 1024 * config.stream_buffer);
Body::wrap_stream(stream)
} else {
let mut contents = vec![];
file.read_to_end(&mut contents).await.unwrap();
Body::from(contents)
};
Ok(Response::builder()
.status(StatusCode::OK)
.header(
header::CONTENT_TYPE,
HeaderValue::from_str(mime_type.as_ref()).unwrap(),
)
.body(body)
.unwrap()
)
},
}
Ok(Response::builder()
.status(StatusCode::OK)
.header(
header::CONTENT_TYPE,
HeaderValue::from_str(mime_type.as_ref()).unwrap(),
)
.body(body)
.unwrap()
)
}


0 comments on commit 801dcda

Please sign in to comment.