handle_static_file_download: optimize small files

Avoid chuncked transfer for small files.
This commit is contained in:
Dietmar Maurer 2018-11-11 17:10:42 +01:00
parent 579fbe7dc8
commit 78d0783b00
1 changed files with 34 additions and 20 deletions

View File

@ -167,26 +167,40 @@ fn handle_sync_api_request<'a>(
fn handle_static_file_download(filename: PathBuf) -> BoxFut { fn handle_static_file_download(filename: PathBuf) -> BoxFut {
let response = File::open(filename) let response = tokio::fs::metadata(filename.clone())
.and_then(|file| { .map_err(|err| format_err!("File access problems: {}", err))
let payload = tokio_codec::FramedRead::new(file, tokio_codec::BytesCodec::new()). .and_then(|metadata| {
map(|bytes| { println!("TEST METADATA {:?} {}", metadata, metadata.len());
//sigh - howto avoid copy here? or the whole map() ??
hyper::Chunk::from(bytes.to_vec()) if metadata.len() < 1024*8 {
}); println!("SMALL SIZED FILE");
let body = Body::wrap_stream(payload); Either::A(File::open(filename)
// fixme: set content type and other headers .map_err(|err| format_err!("File open failed: {}", err))
Ok(Response::builder() .and_then(|file| {
.status(StatusCode::OK) let buf: Vec<u8> = Vec::new();
.body(body) tokio::io::read_to_end(file, buf)
.unwrap()) .map_err(|err| format_err!("File read failed: {}", err))
}) .and_then(|data| Ok(Response::new(data.1.into())))
.or_else(|err| { }))
// fixme: set content type and other headers
Ok(Response::builder() } else {
.status(StatusCode::NOT_FOUND) Either::B(
.body(format!("File access problems: {}\n", err).into()) File::open(filename)
.unwrap()) .map_err(|err| format_err!("File open failed: {}", err))
.and_then(|file| {
let payload = tokio_codec::FramedRead::new(file, tokio_codec::BytesCodec::new()).
map(|bytes| {
//sigh - howto avoid copy here? or the whole map() ??
hyper::Chunk::from(bytes.to_vec())
});
let body = Body::wrap_stream(payload);
// fixme: set content type and other headers
Ok(Response::builder()
.status(StatusCode::OK)
.body(body)
.unwrap())
}))
}
}); });
return Box::new(response); return Box::new(response);