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
use http::header::HeaderValue;
use http::{header, Response};
use context::Context;
use error::Error;
use super::body::ResponseBody;
use super::output::Output;
pub trait Responder {
fn respond_to(self, cx: &Context) -> Result<Output, Error>;
}
impl<T> Responder for Option<T>
where
T: Responder,
{
fn respond_to(self, cx: &Context) -> Result<Output, Error> {
self.ok_or_else(|| Error::not_found())?.respond_to(cx)
}
}
impl<T> Responder for Result<T, Error>
where
T: Responder,
{
fn respond_to(self, cx: &Context) -> Result<Output, Error> {
self?.respond_to(cx)
}
}
impl Responder for Output {
fn respond_to(self, _: &Context) -> Result<Output, Error> {
Ok(self)
}
}
impl<T> Responder for Response<T>
where
T: Into<ResponseBody>,
{
#[inline]
fn respond_to(self, _: &Context) -> Result<Output, Error> {
Ok(self.into())
}
}
impl Responder for &'static str {
#[inline]
fn respond_to(self, _: &Context) -> Result<Output, Error> {
Ok(text_response(self))
}
}
impl Responder for String {
#[inline]
fn respond_to(self, _: &Context) -> Result<Output, Error> {
Ok(text_response(self))
}
}
fn text_response<T: Into<ResponseBody>>(body: T) -> Output {
let mut response = Response::new(body.into());
response.headers_mut().insert(
header::CONTENT_TYPE,
HeaderValue::from_static("text/plain; charset=utf-8"),
);
response.into()
}