3

我想从我的超级服务器提供一些静态文件(.js、.css、...)。
目前我能想到的唯一方法是将文件内联为字符串/在启动时加载它们。
有没有更好的方法来直接提供整个目录或选定的文件?

4

1 回答 1

6

crates.io中输入单词“hyper static”后,第一个结果是hyper-staticfile。该项目的GitHub 存储库有一个示例目录,其中有一个示例:

extern crate futures;
extern crate hyper;
extern crate hyper_staticfile;
extern crate tokio_core;

// This example serves the docs from target/doc/hyper_staticfile at /doc/
//
// Run `cargo doc && cargo run --example doc_server`, then
// point your browser to http://localhost:3000/

use futures::{Future, Stream, future};
use hyper::Error;
use hyper::server::{Http, Request, Response, Service};
use hyper_staticfile::Static;
use std::path::Path;
use tokio_core::reactor::{Core, Handle};
use tokio_core::net::TcpListener;

type ResponseFuture = Box<Future<Item=Response, Error=Error>>;

struct MainService {
    static_: Static,
}

impl MainService {
    fn new(handle: &Handle) -> MainService {
        MainService {
            static_: Static::new(handle, Path::new("target/doc/")),
        }
    }
}

impl Service for MainService {
    type Request = Request;
    type Response = Response;
    type Error = Error;
    type Future = ResponseFuture;

    fn call(&self, req: Request) -> Self::Future {
        if req.path() == "/" {
            let res = Response::new()
                .with_status(hyper::StatusCode::MovedPermanently)
                .with_header(hyper::header::Location::new("/hyper_staticfile/"));
            Box::new(future::ok(res))
        } else {
            self.static_.call(req)
        }
    }
}

fn main() {
    let mut core = Core::new().unwrap();
    let handle = core.handle();

    let addr = "127.0.0.1:3000".parse().unwrap();
    let listener = TcpListener::bind(&addr, &handle).unwrap();

    let http = Http::new();
    let server = listener.incoming().for_each(|(sock, addr)| {
        let s = MainService::new(&handle);
        http.bind_connection(&handle, sock, addr, s);
        Ok(())
    });

    println!("Doc server running on http://localhost:3000/");
    core.run(server).unwrap();
}
于 2017-08-16T12:48:13.397 回答