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
use std::error;
use hyper::StatusCode;
use hyper::header;
use util::NoReturn;
pub use hyper::Response;
pub trait Responder {
type Error: error::Error + Send + 'static;
fn respond(self) -> Result<Response, Self::Error>;
#[doc(hidden)]
fn into_response(self) -> Response
where
Self: Sized,
{
self.respond().unwrap_or_else(|err| {
let message = error::Error::description(&err).to_owned();
Response::new()
.with_status(StatusCode::InternalServerError)
.with_header(header::ContentType::plaintext())
.with_header(header::ContentLength(message.len() as u64))
.with_body(message)
})
}
}
impl Responder for Response {
type Error = NoReturn;
fn respond(self) -> Result<Response, Self::Error> {
Ok(self)
}
}
impl Responder for () {
type Error = NoReturn;
fn respond(self) -> Result<Response, Self::Error> {
Ok(Response::new()
.with_status(StatusCode::NoContent)
.with_header(header::ContentLength(0)))
}
}
impl Responder for &'static str {
type Error = NoReturn;
fn respond(self) -> Result<Response, Self::Error> {
Ok(Response::new()
.with_header(header::ContentType::plaintext())
.with_header(header::ContentLength(self.as_bytes().len() as u64))
.with_body(self))
}
}
impl Responder for String {
type Error = NoReturn;
fn respond(self) -> Result<Response, Self::Error> {
Ok(Response::new()
.with_header(header::ContentType::plaintext())
.with_header(header::ContentLength(self.as_bytes().len() as u64))
.with_body(self))
}
}
#[derive(Debug)]
pub struct Created<T>(pub T);
impl<T: Responder> Responder for Created<T> {
type Error = T::Error;
fn respond(self) -> Result<Response, Self::Error> {
self.0
.respond()
.map(|res| res.with_status(StatusCode::Created))
}
}
#[derive(Debug)]
pub struct NoContent;
impl Responder for NoContent {
type Error = NoReturn;
fn respond(self) -> Result<Response, Self::Error> {
Ok(Response::new().with_status(StatusCode::NoContent))
}
}
#[derive(Debug)]
pub struct ContentType<T>(header::ContentType, T);
impl<T: Responder> ContentType<T> {
pub fn new(content_type: header::ContentType, responder: T) -> Self {
ContentType(content_type, responder)
}
}
impl<T: Responder> Responder for ContentType<T> {
type Error = T::Error;
fn respond(self) -> Result<Response, Self::Error> {
let Self { 0: c, 1: res } = self;
res.respond().map(|res| res.with_header(c))
}
}