From 27cc4c095661838e13082552cc1f951f944fd102 Mon Sep 17 00:00:00 2001 From: Philippe Loctaux Date: Tue, 28 Feb 2023 17:24:57 +0100 Subject: [PATCH] added file_from_bytes --- crates/ezidam/src/file_from_bytes.rs | 29 ++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 crates/ezidam/src/file_from_bytes.rs diff --git a/crates/ezidam/src/file_from_bytes.rs b/crates/ezidam/src/file_from_bytes.rs new file mode 100644 index 0000000..f2dcae9 --- /dev/null +++ b/crates/ezidam/src/file_from_bytes.rs @@ -0,0 +1,29 @@ +use rocket::http::ContentType; +use rocket::response::Responder; +use rocket::{response, Request, Response}; +use std::io::Cursor; + +pub struct FileFromBytes(Vec); + +impl From<&[u8]> for FileFromBytes { + fn from(value: &[u8]) -> Self { + Self(value.to_vec()) + } +} + +#[rocket::async_trait] +impl<'r> Responder<'r, 'static> for FileFromBytes { + fn respond_to(self, _: &'r Request<'_>) -> response::Result<'static> { + // Set HTTP ContentType from guessing the file extension + // Serve file as raw bytes if guessing fails or extension is not supported in Rocket + // Thanks Sergio for the code review! <3 + let content_type = infer::get(&self.0) + .and_then(|mime| ContentType::from_extension(mime.extension())) + .unwrap_or(ContentType::Bytes); + + Response::build() + .header(content_type) + .sized_body(self.0.len(), Cursor::new(self.0)) + .ok() + } +}