gpt4 book ai didi

server - 如何在 hyper 中提供静态文件/目录?

转载 作者:行者123 更新时间:2023-11-29 07:58:06 30 4
gpt4 key购买 nike

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

最佳答案

crates.io 中输入“hyper static”之后, 第一个结果是 hyper-staticfile .该项目的GitHub repository有一个 examples directory ,举一个这样的例子:

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

关于server - 如何在 hyper 中提供静态文件/目录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45713444/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com