forked from hyperium/hyper
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.rs
69 lines (54 loc) · 1.87 KB
/
server.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// You have to ctrl-C after running this benchmark, since there is no way to kill
// a rust-http server.
extern crate http;
extern crate hyper;
extern crate test;
use test::Bencher;
use std::io::net::ip::{SocketAddr, Ipv4Addr};
use http::server::Server;
use hyper::server::{Request, Response};
static PHRASE: &'static [u8] = b"Benchmarking hyper vs others!";
fn request(url: hyper::Url) {
let req = hyper::client::Request::get(url).unwrap();
req.start().unwrap().send().unwrap().read_to_string().unwrap();
}
fn hyper_handle(_: Request, res: Response) {
let mut res = res.start().unwrap();
res.write(PHRASE).unwrap();
res.end().unwrap();
}
#[bench]
fn bench_hyper(b: &mut Bencher) {
let server = hyper::Server::http(Ipv4Addr(127, 0, 0, 1), 0);
let mut listener = server.listen(hyper_handle).unwrap();
let url = hyper::Url::parse(format!("http://{}", listener.socket).as_slice()).unwrap();
b.iter(|| request(url.clone()));
listener.close().unwrap();
}
static mut created_http: bool = false;
#[deriving(Clone)]
struct HttpServer;
impl Server for HttpServer {
fn get_config(&self) -> http::server::Config {
http::server::Config {
bind_address: SocketAddr {
ip: Ipv4Addr(127, 0, 0, 1),
port: 4000
}
}
}
fn handle_request(&self, _: http::server::Request, res: &mut http::server::ResponseWriter) {
res.write(PHRASE).unwrap();
}
}
#[bench]
fn bench_http(b: &mut Bencher) {
if unsafe { !created_http } {
spawn(proc() { HttpServer.serve_forever() });
unsafe { created_http = true }
// Mega hack because there is no way to wait for serve_forever to start:
std::io::timer::sleep(std::time::duration::Duration::seconds(1));
}
let url = hyper::Url::parse("http://localhost:4000").unwrap();
b.iter(|| request(url.clone()));
}