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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
extern crate hyper;
use std::sync::Arc;
use std::collections::HashMap;
use std::time::Duration;
use hyper::Server as HyperServer;
use futures_cpupool::CpuPool;
use crate::{Context, Handler, Protocol, CatcherImpl, Catcher};
use crate::http::{self, StatusCode, Request, Response, MediaType};
use crate::catcher;
use std::net::{SocketAddr, ToSocketAddrs};
use futures::{future, Future};
#[derive(Debug, PartialEq, Clone, Copy)]
pub struct Timeouts {
pub keep_alive: Option<Duration>,
}
impl Default for Timeouts {
fn default() -> Self {
Timeouts {
keep_alive: Some(Duration::from_secs(5)),
}
}
}
pub struct Server<H> {
pub handler: Arc<H>,
pub timeouts: Timeouts,
pub pool: CpuPool,
pub protocol: Protocol,
pub local_addr: Option<SocketAddr>,
pub catchers: Arc<Vec<Box<dyn Catcher>>>,
pub media_types: Arc<HashMap<String, MediaType>>,
}
impl<H: Handler> Server<H> {
pub fn new(handler: H)->Server<H>{
Server{
handler: Arc::new(handler),
protocol: Protocol::http(),
local_addr: None,
timeouts: Timeouts::default(),
pool: CpuPool::new_num_cpus(),
catchers: Arc::new(catcher::defaults::get()),
media_types: Arc::new(http::media_type::defaults::get()),
}
}
pub fn serve<A>(mut self, addr: A) where A: ToSocketAddrs{
let addr: SocketAddr = addr.to_socket_addrs().unwrap().next().unwrap();
self.local_addr = Some(addr);
let server = HyperServer::bind(&addr)
.serve(self).map_err(|e| eprintln!("server error: {}", e));
hyper::rt::run(server);
}
}
impl<H: Handler> hyper::service::NewService for Server<H> {
type ReqBody = hyper::body::Body;
type ResBody = hyper::body::Body;
type Error = hyper::Error;
type Service = HyperHandler<H>;
type InitError = hyper::Error;
type Future = future::FutureResult<Self::Service, Self::InitError>;
fn new_service(&self) -> Self::Future {
future::ok(HyperHandler {
handler: self.handler.clone(),
addr: self.local_addr,
protocol: self.protocol.clone(),
pool: self.pool.clone(),
catchers: self.catchers.clone(),
media_types: self.media_types.clone(),
})
}
}
pub struct HyperHandler<H> {
handler: Arc<H>,
addr: Option<SocketAddr>,
protocol: Protocol,
pool: CpuPool,
catchers: Arc<Vec<Box<dyn Catcher>>>,
media_types: Arc<HashMap<String, MediaType>>,
}
impl<H: Handler> hyper::service::Service for HyperHandler<H>{
type ReqBody = hyper::body::Body;
type ResBody = hyper::body::Body;
type Error = hyper::Error;
type Future = Box<dyn Future<Item = hyper::Response<Self::ResBody>, Error = Self::Error> + Send>;
fn call(&mut self, req: hyper::Request<Self::ReqBody>) -> Self::Future {
let addr = self.addr;
let proto = self.protocol.clone();
let handler = self.handler.clone();
let catchers = self.catchers.clone();
Box::new(self.pool.spawn_fn(move || {
let mut ctx = Context::new(Request::from_hyper(req, addr, &proto).unwrap(), Response::new());
handler.handle(&mut ctx);
if !ctx.is_commited() {
ctx.commit();
}
let mut response = hyper::Response::<hyper::Body>::new(hyper::Body::empty());
if ctx.response.body_writers.len() == 0 {
(&mut ctx.response).status = Some(StatusCode::NOT_FOUND);
}else if let None = ctx.response.status{
(&mut ctx.response).status = Some(StatusCode::OK);
}
if let None = ctx.response.status {
ctx.response.status = Some(StatusCode::NOT_FOUND);
}
let status = ctx.response.status.unwrap();
if ctx.response.body_writers.len() == 0 && !status.as_str().starts_with("2") {
for catcher in &*catchers {
if catcher.catch(&ctx.request, &mut ctx.response){
break;
}
}
}
ctx.response.write_back(&mut response, ctx.request.method.clone());
future::ok(response)
}))
}
}