4 changed files with 76 additions and 2 deletions
@ -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…
Reference in new issue