Rocket doesn't natively impl Responder for &[u8] so we need to wrap it and implement it ourselves.

This commit is contained in:
Adrian Malacoda 2017-10-26 00:13:06 -05:00
parent e4fe6ff37f
commit 0b87d77759

View File

@ -78,14 +78,22 @@ impl ResourcesGenerator {
if let Some(ref mount_at) = resource.mount_at {
let mut function_name = String::from("route");
let mut function_return_type = "&'static str";
let mut function_return_value = String::from(resource.constant.unwrap_or(&include));
if resource.raw {
function_return_type = "RawByteResource";
function_return_value = format!("RawByteResource({})", function_return_value);
}
function_name.push_str(&mount_at.endpoint.replace("/", "_").replace(".", "_").replace("-", "_"));
routes.push_str(&format!(
"#[get(\"{}\")]\nfn {}() -> Content<&'static {}> {{\n\tContent(ContentType::{}, {})\n}}\n\n",
"#[get(\"{}\")]\nfn {}() -> Content<{}> {{\n\tContent(ContentType::{}, {})\n}}\n\n",
mount_at.endpoint,
function_name,
data_type,
function_return_type,
mount_at.content_type,
resource.constant.unwrap_or(&include)
function_return_value
));
routes_fn.push_str(&function_name);
routes_fn.push(',');
@ -102,7 +110,17 @@ impl ResourcesGenerator {
}
if !routes.is_empty() {
outfile.write(b"use rocket::Route;\nuse rocket::response::Content;\nuse rocket::http::ContentType;\n\n");
outfile.write(b"use rocket::{Route, Response, Request};\nuse rocket::response::{Content, Responder};\nuse rocket::http::{ContentType, Status};\n\n");
outfile.write(b"use std::io::Cursor;\n\n");
outfile.write(b"struct RawByteResource(&'static [u8]);\n");
outfile.write(b"impl<'r> Responder<'r> for RawByteResource {
fn respond_to(self, _: &Request) -> Result<Response<'r>, Status> {
Response::build()
.header(ContentType::Binary)
.sized_body(Cursor::new(self.0))
.ok()
}
}");
}
if !handlebars.is_empty () {