refactor: handler zip
parent
06d2b81824
commit
8900dde7e7
|
@ -5,7 +5,6 @@ use async_zip::write::{EntryOptions, ZipFileWriter};
|
||||||
use async_zip::Compression;
|
use async_zip::Compression;
|
||||||
use futures::stream::StreamExt;
|
use futures::stream::StreamExt;
|
||||||
use futures::TryStreamExt;
|
use futures::TryStreamExt;
|
||||||
use hyper::body::Bytes;
|
|
||||||
use hyper::header::HeaderValue;
|
use hyper::header::HeaderValue;
|
||||||
use hyper::service::{make_service_fn, service_fn};
|
use hyper::service::{make_service_fn, service_fn};
|
||||||
use hyper::{Body, Method, StatusCode};
|
use hyper::{Body, Method, StatusCode};
|
||||||
|
@ -16,10 +15,10 @@ use std::path::{Path, PathBuf};
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use std::time::SystemTime;
|
use std::time::SystemTime;
|
||||||
use tokio::fs::File;
|
use tokio::fs::File;
|
||||||
use tokio::io::{AsyncReadExt, AsyncWrite};
|
use tokio::io::AsyncWrite;
|
||||||
use tokio::{fs, io};
|
use tokio::{fs, io};
|
||||||
use tokio_util::codec::{BytesCodec, FramedRead};
|
use tokio_util::codec::{BytesCodec, FramedRead};
|
||||||
use tokio_util::io::StreamReader;
|
use tokio_util::io::{ReaderStream, StreamReader};
|
||||||
|
|
||||||
type Request = hyper::Request<Body>;
|
type Request = hyper::Request<Body>;
|
||||||
type Response = hyper::Response<Body>;
|
type Response = hyper::Response<Body>;
|
||||||
|
@ -188,27 +187,15 @@ impl InnerService {
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn handle_send_dir_zip(&self, path: &Path) -> BoxResult<Response> {
|
async fn handle_send_dir_zip(&self, path: &Path) -> BoxResult<Response> {
|
||||||
let (mut tx, body) = Body::channel();
|
let (mut writer, reader) = tokio::io::duplex(BUF_SIZE);
|
||||||
let (mut writer, mut reader) = tokio::io::duplex(BUF_SIZE);
|
|
||||||
let path = path.to_owned();
|
let path = path.to_owned();
|
||||||
tokio::spawn(async move {
|
tokio::spawn(async move {
|
||||||
if let Err(e) = dir_zip(&mut writer, &path).await {
|
if let Err(e) = dir_zip(&mut writer, &path).await {
|
||||||
error!("Fail to zip {}, {}", path.display(), e.to_string());
|
error!("Fail to zip {}, {}", path.display(), e.to_string());
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
tokio::spawn(async move {
|
let stream = ReaderStream::new(reader);
|
||||||
// Reuse this buffer
|
let body = Body::wrap_stream(stream);
|
||||||
let mut buf = [0_u8; BUF_SIZE];
|
|
||||||
loop {
|
|
||||||
let n = reader.read(&mut buf).await.unwrap();
|
|
||||||
if n == 0 {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
if (tx.send_data(Bytes::from(buf[..n].to_vec())).await).is_err() {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
Ok(Response::new(body))
|
Ok(Response::new(body))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue