This seems to be working fine, but it performance testing with wrk
is poor compared to what I've come up in other languages. Shouldn't Rust excel in serving static files?
- How can I make this faster?
- Are there any other potential problems here?
extern crate hyper;
extern crate futures;
use std::fs::File;
use std::io::Read;
use std::path::Path;
use std::ffi::OsStr;
use hyper::StatusCode;
use futures::future::FutureResult;
use hyper::server::{Http, Service, Request, Response};
mod api;
struct Router;
impl Service for Router {
type Request = Request;
type Response = Response;
type Error = hyper::Error;
type Future = FutureResult<Response, hyper::Error>;
fn call(&self, req: Request) -> Self::Future {
futures::future::ok(match req.path() {
"/json" => api::default::json(req),
_ => static_file(req.path()),
})
}
}
fn main() {
let addr = "127.0.0.1:5000".parse().unwrap();
let server = Http::new().bind(&addr, || Ok(Router)).unwrap();
println!("Listening on http://{} with 1 thread...", server.local_addr().unwrap());
server.run().unwrap();
}
pub fn static_file(path: &str) -> Response {
let mut f = match File::open("src/static".to_owned() + path) {
Ok(f) => f,
Err(_) => {
return Response::new().with_status(StatusCode::NotFound)
},
};
let mut data = String::new();
match f.read_to_string(&mut data) {
Ok(_) => {},
Err(_) => {
return Response::new().with_status(StatusCode::NotFound)
},
};
let mut headers = hyper::header::Headers::new();
match Path::new(&path).extension().and_then(OsStr::to_str) {
Some(ext) => match ext {
"html" => headers.set_raw("Content-Type", "text/html"),
"css" => headers.set_raw("Content-Type", "text/css"),
"js" => headers.set_raw("Content-Type", "application/javascript"),
_ => headers.set_raw("Content-Type", "text/plain"),
},
None => headers.set_raw("Content-Type", "text/plain"),
};
Response::new()
.with_status(StatusCode::Ok)
.with_headers(headers)
.with_body(data)
}
api
module so no answerer will be able to actually compile and test your code so see if it's slow or fast. \$\endgroup\$