6

我正在尝试include_bytes!在 Iron 应用程序中发送一个包含在二进制文件中的文件。我想为我的应用程序提供一个文件,它只需要很少的 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某种方式实现这个特性?

4

1 回答 1

11

编译器提出了一个替代方案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在文档中找到实现,但不幸的是,我认为它们没有列出。Modifier<Response>但是,我在模块的源代码中iron::modifiers找到了一些实现。

于 2016-01-24T19:06:23.820 回答