]> git.proxmox.com Git - proxmox-backup.git/blob - src/api2/helpers.rs
api: rustfmt
[proxmox-backup.git] / src / api2 / helpers.rs
1 use std::path::PathBuf;
2
3 use anyhow::Error;
4 use futures::stream::TryStreamExt;
5 use hyper::{header, Body, Response, StatusCode};
6
7 use proxmox_router::http_bail;
8
9 pub async fn create_download_response(path: PathBuf) -> Result<Response<Body>, Error> {
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 };
17
18 let payload = tokio_util::codec::FramedRead::new(file, tokio_util::codec::BytesCodec::new())
19 .map_ok(|bytes| 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 }