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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
use futures::{Future, Stream};
use hyper::server::conn::Http;
use log::info;
use std::net::ToSocketAddrs;
use std::sync::Arc;
use tokio::executor;
use tokio::net::TcpListener;
use tokio::runtime::TaskExecutor;
use super::{handler::NewHandler, service::GothamService};
use super::{new_runtime, tcp_listener};
pub mod test;
pub fn start<NH, A>(addr: A, new_handler: NH)
where
NH: NewHandler + 'static,
A: ToSocketAddrs + 'static,
{
start_with_num_threads(addr, new_handler, num_cpus::get())
}
pub fn start_with_num_threads<NH, A>(addr: A, new_handler: NH, threads: usize)
where
NH: NewHandler + 'static,
A: ToSocketAddrs + 'static,
{
let runtime = new_runtime(threads);
start_on_executor(addr, new_handler, runtime.executor());
runtime.shutdown_on_idle().wait().unwrap();
}
pub fn start_on_executor<NH, A>(addr: A, new_handler: NH, executor: TaskExecutor)
where
NH: NewHandler + 'static,
A: ToSocketAddrs + 'static,
{
executor.spawn(init_server(addr, new_handler));
}
pub fn init_server<NH, A>(addr: A, new_handler: NH) -> impl Future<Item = (), Error = ()>
where
NH: NewHandler + 'static,
A: ToSocketAddrs + 'static,
{
let listener = tcp_listener(addr);
let addr = listener.local_addr().unwrap();
info!(
target: "gotham::start",
" Gotham listening on http://{}",
addr
);
bind_server(listener, new_handler)
}
fn bind_server<NH>(listener: TcpListener, new_handler: NH) -> impl Future<Item = (), Error = ()>
where
NH: NewHandler + 'static,
{
let protocol = Arc::new(Http::new());
let gotham_service = GothamService::new(new_handler);
listener
.incoming()
.map_err(|e| panic!("socket error = {:?}", e))
.for_each(move |socket| {
let addr = socket.peer_addr().unwrap();
let service = gotham_service.connect(addr);
let handler = protocol.serve_connection(socket, service).then(|_| Ok(()));
executor::spawn(handler);
Ok(())
})
}