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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
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 tokio_rustls::{rustls, TlsAcceptor};
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, tls_config: rustls::ServerConfig)
where
NH: NewHandler + 'static,
A: ToSocketAddrs + 'static,
{
start_with_num_threads(addr, new_handler, tls_config, num_cpus::get())
}
pub fn start_with_num_threads<NH, A>(
addr: A,
new_handler: NH,
tls_config: rustls::ServerConfig,
threads: usize,
) where
NH: NewHandler + 'static,
A: ToSocketAddrs + 'static,
{
let runtime = new_runtime(threads);
start_on_executor(addr, new_handler, tls_config, runtime.executor());
runtime.shutdown_on_idle().wait().unwrap();
}
pub fn start_on_executor<NH, A>(
addr: A,
new_handler: NH,
tls_config: rustls::ServerConfig,
executor: TaskExecutor,
) where
NH: NewHandler + 'static,
A: ToSocketAddrs + 'static,
{
executor.spawn(init_server(addr, new_handler, tls_config));
}
pub fn init_server<NH, A>(
addr: A,
new_handler: NH,
tls_config: rustls::ServerConfig,
) -> 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, tls_config)
}
fn bind_server<NH>(
listener: TcpListener,
new_handler: NH,
tls_config: rustls::ServerConfig,
) -> impl Future<Item = (), Error = ()>
where
NH: NewHandler + 'static,
{
let protocol = Arc::new(Http::new());
let gotham_service = GothamService::new(new_handler);
let tls = TlsAcceptor::from(Arc::new(tls_config));
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 accepted_protocol = protocol.clone();
let handler = tls
.accept(socket)
.map_err(|e| panic!("https error = {:?}", e))
.and_then(move |socket| {
accepted_protocol
.serve_connection(socket, service)
.map_err(|e| panic!("http error = {:?}", e))
});
executor::spawn(handler);
Ok(())
})
}