Browse Source

pieced together some hyper file serving

master
Weird Constructor 4 years ago
parent
commit
eb9804ad10
  1. 1
      Cargo.lock
  2. 1
      Cargo.toml
  3. 4
      build.rs
  4. 72
      src/main.rs

1
Cargo.lock generated

@ -663,6 +663,7 @@ dependencies = [
name = "weird_goban"
version = "0.1.0"
dependencies = [
"futures 0.1.27 (registry+https://github.com/rust-lang/crates.io-index)",
"hyper 0.12.29 (registry+https://github.com/rust-lang/crates.io-index)",
"serde 1.0.92 (registry+https://github.com/rust-lang/crates.io-index)",
]

1
Cargo.toml

@ -8,3 +8,4 @@ build="build.rs"
[dependencies]
hyper="0.12.29"
serde="1.0.92"
futures="0.1"

4
build.rs

@ -9,6 +9,8 @@ fn main() {
let s = Command::new("cmd").args(&["/C", "_WEBPACK.bat"]).status().unwrap();
if !s.success() { panic!("Webpack failed"); }
} else {
Command::new("webpack").status().unwrap();
let s = Command::new("node_modules/.bin/webpack").status().unwrap();
if !s.success() { panic!("Webpack failed"); }
std::fs::copy("webdata/dist/index.html", "webdata/index.html").unwrap();
}
}

72
src/main.rs

@ -1,3 +1,73 @@
extern crate hyper;
extern crate futures;
use hyper::{Body, Request, Response, Server, Method, StatusCode};
use hyper::rt::Future;
use hyper::service::service_fn;
use hyper::header::{HeaderName, HeaderValue};
use futures::future;
use std::path::Path;
type BoxFut = Box<dyn Future<Item=Response<Body>, Error=hyper::Error> + Send>;
fn mime_for_ext(s: &str) -> String {
String::from(
match s {
"css" => "text/css",
"js" => "text/javascript",
"json" => "application/json",
"html" => "text/html",
_ => "text/plain",
}
)
}
fn hello_world(req: Request<Body>) -> BoxFut {
let mut response = Response::new(Body::empty());
match (req.method(), req.uri().path()) {
(&Method::GET, "/") => {
*response.body_mut() = Body::from("Try POSTing data to /echo");
},
(&Method::POST, "/echo") => {
*response.body_mut() = Body::from("WURST");
},
(&Method::GET, path) => {
let npath : String = path.chars().skip(1).collect();
let as_path = Path::new(&npath);
println!("GET PATH: {}", npath);
if as_path.is_file() {
let text = vec![std::fs::read(as_path).unwrap()];
if let Some(extension) = as_path.extension() {
let mime = mime_for_ext(extension.to_str().unwrap());
(*response.headers_mut()).insert(
HeaderName::from_static("content-type"),
HeaderValue::from_str(&mime).unwrap());
} else {
eprintln!("Content type unset for {:?}", as_path);
}
*response.body_mut() =
Body::wrap_stream(futures::stream::iter_ok::<_, ::std::io::Error>(text));
}
},
_ => {
*response.status_mut() = StatusCode::NOT_FOUND;
},
};
Box::new(future::ok(response))
}
fn main() {
println!("Hello, world!");
let addr = ([127, 0, 0, 1], 19099).into();
let server = Server::bind(&addr)
.serve(|| service_fn(hello_world))
.map_err(|e| eprintln!("server error: {}", e));
// Run this server for... forever!
hyper::rt::run(server);
}

Loading…
Cancel
Save