]>
Commit | Line | Data |
---|---|---|
e22f4882 | 1 | use std::path::PathBuf; |
8aa67ee7 | 2 | |
e22f4882 | 3 | use anyhow::Error; |
8aa67ee7 | 4 | use futures::stream::TryStreamExt; |
e22f4882 | 5 | use hyper::{Body, Response, StatusCode, header}; |
8aa67ee7 WB |
6 | |
7 | use proxmox::http_bail; | |
e22f4882 SR |
8 | |
9 | pub async fn create_download_response(path: PathBuf) -> Result<Response<Body>, Error> { | |
8aa67ee7 WB |
10 | let file = match tokio::fs::File::open(path.clone()).await { |
11 | Ok(file) => file, | |
12 | Err(ref err) if err.kind() == std::io::ErrorKind::NotFound => { | |
13 | http_bail!(NOT_FOUND, "open file {:?} failed - not found", path); | |
14 | } | |
15 | Err(err) => http_bail!(BAD_REQUEST, "open file {:?} failed: {}", path, err), | |
16 | }; | |
e22f4882 SR |
17 | |
18 | let payload = tokio_util::codec::FramedRead::new(file, tokio_util::codec::BytesCodec::new()) | |
19 | .map_ok(|bytes| hyper::body::Bytes::from(bytes.freeze())); | |
20 | ||
21 | let body = Body::wrap_stream(payload); | |
22 | ||
23 | // fixme: set other headers ? | |
24 | Ok(Response::builder() | |
25 | .status(StatusCode::OK) | |
26 | .header(header::CONTENT_TYPE, "application/octet-stream") | |
27 | .body(body) | |
28 | .unwrap()) | |
29 | } |