问题
I'm trying to send a file that I included in the binary with include_bytes!
in an Iron application. I want to end up with a single file for my application and it only needs very few HTML, CSS and JS files. Here's a small test setup that I'm fiddling with:
extern crate iron;
use iron::prelude::*;
use iron::status;
use iron::mime::Mime;
fn main() {
let index_html = include_bytes!("static/index.html");
println!("Hello, world!");
Iron::new(| _: &mut Request| {
let content_type = "text/html".parse::<Mime>().unwrap();
Ok(Response::with((content_type, status::Ok, index_html)))
}).http("localhost:8001").unwrap();
}
Of course, this doesn't work since index_html
is of type &[u8; 78]
src/main.rs:16:12: 16:26 error: the trait `modifier::Modifier<iron::response::Response>` is not implemented for the type `&[u8; 78]` [E0277]
src/main.rs:16 Ok(Response::with((content_type, status::Ok, index_html)))
Since I'm quite new to Rust and Iron, I don't have an idea how to approach this. I tried to learn something from the Iron docs but I think my Rust knowledge is not sufficient to really understand them, especially what this modifier::Modifier
trait is supposed to be.
How can I achieve this? Can I covert the type of my static resource into something that Iron will accept or do I need to implement this Modifier
trait somehow?
回答1:
The compiler suggests an alternative impl
:
src/main.rs:13:12: 13:26 help: the following implementations were found:
src/main.rs:13:12: 13:26 help: <&'a [u8] as modifier::Modifier<iron::response::Response>>
To ensure the slice lives long enough, it's easier to replace the index_html
variable with a global constant, and since we must specify the type of constants, let's specify it as &'static [u8]
.
extern crate iron;
use iron::prelude::*;
use iron::status;
use iron::mime::Mime;
const INDEX_HTML: &'static [u8] = include_bytes!("static/index.html");
fn main() {
println!("Hello, world!");
Iron::new(| _: &mut Request| {
let content_type = "text/html".parse::<Mime>().unwrap();
Ok(Response::with((content_type, status::Ok, INDEX_HTML)))
}).http("localhost:8001").unwrap();
}
By the way, I tried to find implementations for Modifier
in the documentation, but I think they're not listed, unfortunately. However, I found some implementations for Modifier<Response>
in the source for the iron::modifiers module.
来源:https://stackoverflow.com/questions/34979970/how-do-i-send-a-file-included-with-include-bytes-as-an-iron-response