How do I send a file included with include_bytes! as an Iron response?

你说的曾经没有我的故事 提交于 2019-12-10 13:44:54

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!