如何发送include_bytes附带的文件!作为铁响应?

时间:2016-01-24 18:52:41

标签: rust iron

我尝试在Iron应用程序中使用include_bytes!发送包含在二进制文件中的文件。我想最终为我的应用程序提供一个文件,它只需要很少的HTML,CSS和JS文件。这是一个小型测试设置,我正在摆弄:

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();
}

当然,由于index_html的类型为&[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)))

由于我对Rust和Iron很陌生,所以我不知道如何处理这个问题。我试图从Iron文档中学到一些东西,但我认为我的Rust知识不足以真正理解它们,特别是这个modifier::Modifier特性应该是什么。

我怎样才能做到这一点?我是否可以将我的静态资源类型转换为Iron将接受的内容,或者我需要以某种方式实现此Modifier特征?

1 个答案:

答案 0 :(得分:7)

编译器建议另一个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>>

为了确保切片的寿命足够长,使用全局常量替换index_html变量更容易,因为我们必须指定常量的类型,所以我们将其指定为&'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();
}

顺便说一句,我试图在文档中找到Modifier的实现,但不幸的是我认为它们没有列出。但是,我在the source for the iron::modifiers module中找到了Modifier<Response>的一些实现。