Files
hyper/examples/server.rs
Jonathan Reem 3528fb9b01 feat(server): Rewrite the accept loop into a custom thread pool.
This is a modified and specialized thread pool meant for
managing an acceptor in a multi-threaded way. A single handler
is provided which will be invoked on each stream.

Unlike the old thread pool, this returns a join guard which
will block until the acceptor closes, enabling friendly behavior
for the listening guard.

The task pool itself is also faster as it only pays for message passing
if sub-threads panic. In the optimistic case where there are few panics,
this saves using channels for any other communication.

This improves performance by around 15%, all the way to 105k req/sec
on my machine, which usually gets about 90k.

BREAKING_CHANGE: server::Listening::await is removed.
2015-02-14 13:54:57 -08:00

57 lines
1.6 KiB
Rust

#![feature(io)]
extern crate hyper;
#[macro_use] extern crate log;
use std::old_io::util::copy;
use std::old_io::net::ip::Ipv4Addr;
use hyper::{Get, Post};
use hyper::header::ContentLength;
use hyper::server::{Server, Request, Response};
use hyper::uri::RequestUri::AbsolutePath;
macro_rules! try_return(
($e:expr) => {{
match $e {
Ok(v) => v,
Err(e) => { error!("Error: {}", e); return; }
}
}}
);
fn echo(mut req: Request, mut res: Response) {
match req.uri {
AbsolutePath(ref path) => match (&req.method, &path[]) {
(&Get, "/") | (&Get, "/echo") => {
let out = b"Try POST /echo";
res.headers_mut().set(ContentLength(out.len() as u64));
let mut res = try_return!(res.start());
try_return!(res.write_all(out));
try_return!(res.end());
return;
},
(&Post, "/echo") => (), // fall through, fighting mutable borrows
_ => {
*res.status_mut() = hyper::NotFound;
try_return!(res.start().and_then(|res| res.end()));
return;
}
},
_ => {
try_return!(res.start().and_then(|res| res.end()));
return;
}
};
let mut res = try_return!(res.start());
try_return!(copy(&mut req, &mut res));
try_return!(res.end());
}
fn main() {
let server = Server::http(Ipv4Addr(127, 0, 0, 1), 1337);
let _guard = server.listen(echo).unwrap();
println!("Listening on http://127.0.0.1:1337");
}