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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
use hyper::header::{CookiePair as Cookie, ContentLength, ContentType, Header, Location, SetCookie};
use hyper::status::StatusCode as Status;
use hyper::{Control, Headers, Next};
use hyper::mime::{Mime, TopLevel, SubLevel, Attr, Value};
use handlebars::Handlebars;
use serde::ser::Serialize as ToJson;
pub use serde_json::value as value;
use std::fmt::Debug;
use std::borrow::Cow;
use std::io::{ErrorKind, Read, Result, Write};
use std::fs::{File, read_dir};
use std::path::Path;
use std::cell::RefCell;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use buffer::Buffer;
#[derive(Debug)]
pub struct Resp {
status: RefCell<Status>,
headers: RefCell<Headers>,
body: RefCell<Buffer>,
notify: AtomicBool,
ctrl: Control
}
unsafe impl Sync for Resp {}
impl Resp {
pub fn new(ctrl: Control) -> Resp {
Resp {
status: RefCell::new(Status::Ok),
headers: RefCell::new(Headers::default()),
body: RefCell::new(Buffer::new()),
notify: AtomicBool::new(false),
ctrl: ctrl
}
}
fn status(&self, status: Status) {
*self.status.borrow_mut() = status;
}
fn has_header<H: Header>(&self) -> bool {
self.headers.borrow().has::<H>()
}
fn header<H: Header>(&self, header: H) {
self.headers.borrow_mut().set(header);
}
fn header_raw<K: Into<Cow<'static, str>> + Debug>(&self, name: K, value: Vec<Vec<u8>>) {
self.headers.borrow_mut().set_raw(name, value);
}
fn push_cookie(&self, cookie: Cookie) {
self.headers.borrow_mut().get_mut::<SetCookie>().unwrap().push(cookie)
}
fn len(&self) -> usize {
self.body.borrow().len()
}
fn append<D: AsRef<[u8]>>(&self, content: D) {
self.body.borrow_mut().append(content.as_ref());
}
fn send<D: Into<Vec<u8>>>(&self, content: D) {
self.body.borrow_mut().send(content);
}
pub fn deconstruct(self) -> (Status, Headers, Buffer) {
(self.status.into_inner(),
self.headers.into_inner(),
self.body.into_inner())
}
fn done(&self) {
if self.notify.load(Ordering::Acquire) {
self.ctrl.ready(Next::write()).unwrap();
}
}
}
pub fn set_notify(resp: &Option<Arc<Resp>>) {
if let Some(ref arc) = *resp {
arc.notify.store(true, Ordering::Release);
}
}
pub struct Response {
resp: Option<Arc<Resp>>
}
impl Drop for Response {
fn drop(&mut self) {
let resp = self.resp.as_ref().unwrap().as_ref() as *const Resp;
{
self.resp.take().unwrap();
}
unsafe {
(*resp).done();
}
}
}
fn register_partials(handlebars: &mut Handlebars) -> Result<()> {
for it in try!(read_dir("views/partials")) {
let entry = try!(it);
let path = entry.path();
if path.extension().is_some() && path.extension().unwrap() == "hbs" {
let name = path.file_stem().unwrap().to_str().unwrap();
handlebars.register_template_file(name, path.as_path()).unwrap();
}
}
Ok(())
}
pub fn new(resp: &Option<Arc<Resp>>) -> Response {
Response {
resp: Some(resp.as_ref().unwrap().clone())
}
}
impl Response {
fn resp(&self) -> &Resp {
&self.resp.as_ref().unwrap()
}
pub fn status(&mut self, status: Status) -> &mut Self {
self.resp().status(status);
self
}
pub fn content_type<S: Into<Vec<u8>>>(&mut self, mime: S) -> &mut Self {
self.header_raw("Content-Type", mime)
}
pub fn len(&mut self, len: u64) -> &mut Self {
self.header(ContentLength(len))
}
pub fn location<S: Into<String>>(&mut self, url: S) -> &mut Self {
self.header(Location(url.into()))
}
pub fn redirect(mut self, url: &str, status: Option<Status>) {
self.location(url);
self.end(status.unwrap_or(Status::Found))
}
pub fn header<H: Header>(&mut self, header: H) -> &mut Self {
self.resp().header(header);
self
}
pub fn header_raw<K: Into<Cow<'static, str>> + Debug, V: Into<Vec<u8>>>(&mut self, name: K, value: V) -> &mut Self {
self.resp().header_raw(name, vec![value.into()]);
self
}
pub fn end(mut self, status: Status) {
self.status(status);
self.len(0);
}
pub fn render<P: AsRef<Path>, T: ToJson>(self, path: P, data: T) {
let mut handlebars = Handlebars::new();
let path = path.as_ref();
let name = path.file_stem().unwrap().to_str().unwrap();
handlebars.register_template_file(name, path).unwrap();
register_partials(&mut handlebars).unwrap();
let result = handlebars.render(name, &data);
self.send(result.unwrap())
}
pub fn send<D: Into<Vec<u8>>>(mut self, content: D) {
self.resp().send(content);
let length = self.resp().len();
self.len(length as u64);
}
pub fn append<D: AsRef<[u8]>>(&mut self, content: D) {
self.resp().append(content);
let length = self.resp().len() as u64;
self.len(length);
}
pub fn send_file<P: AsRef<Path>>(mut self, path: P) {
if !self.resp().has_header::<ContentType>() {
let extension = path.as_ref().extension();
if let Some(ext) = extension {
let content_type = match ext.to_string_lossy().as_ref() {
"htm" | "html" => Some(ContentType::html()),
"jpg" | "jpeg" => Some(ContentType::jpeg()),
"png" => Some(ContentType::png()),
"js" => Some(ContentType(Mime(TopLevel::Text, SubLevel::Javascript, vec![(Attr::Charset, Value::Utf8)]))),
"css" => Some(ContentType(Mime(TopLevel::Text, SubLevel::Css, vec![(Attr::Charset, Value::Utf8)]))),
_ => None
};
if let Some(content_type) = content_type {
self.resp().header(content_type);
}
}
}
match File::open(path) {
Ok(mut file) => {
let mut buf = Vec::with_capacity(file.metadata().ok().map_or(1024, |meta| meta.len() as usize));
if let Err(err) = file.read_to_end(&mut buf) {
self.status(Status::InternalServerError).content_type("text/plain");
self.send(format!("{}", err))
} else {
self.send(buf)
}
},
Err(ref err) if err.kind() == ErrorKind::NotFound => self.end(Status::NotFound),
Err(ref err) => {
self.status(Status::InternalServerError).content_type("text/plain");
self.send(format!("{}", err))
}
}
}
pub fn cookie(&mut self, cookie: Cookie) {
if self.resp().has_header::<SetCookie>() {
self.resp().push_cookie(cookie)
} else {
self.resp().header(SetCookie(vec![cookie]))
}
}
}