added file_from_bytes
This commit is contained in:
parent
95b908836e
commit
27cc4c0956
1 changed files with 29 additions and 0 deletions
29
crates/ezidam/src/file_from_bytes.rs
Normal file
29
crates/ezidam/src/file_from_bytes.rs
Normal file
|
|
@ -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<u8>);
|
||||
|
||||
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()
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue