我正在尝试在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特性?

最佳答案

编译器建议使用另一种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 Modifier<Response> module中找到了iron::modifiers的一些实现。

关于rust - 如何发送include_bytes包含的文件!作为铁的回应?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34979970/

10-12 20:09