Skip to main content

rustlavel_http/
response.rs

1use crate::cookie::Cookie;
2use crate::headers::Headers;
3use crate::status::Status;
4use rustlavel_core::{Error, Json};
5
6/// An outgoing response.
7#[derive(Clone)]
8pub struct Response {
9    pub status: Status,
10    pub headers: Headers,
11    pub body: Vec<u8>,
12    /// Set when the handler answered `101` and wants the socket.
13    pub(crate) upgrade: Option<crate::upgrade::Upgrader>,
14}
15
16impl std::fmt::Debug for Response {
17    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
18        f.debug_struct("Response")
19            .field("status", &self.status)
20            .field("headers", &self.headers)
21            .field("body_len", &self.body.len())
22            .field("upgrades", &self.upgrade.is_some())
23            .finish()
24    }
25}
26
27impl Response {
28    pub fn new(status: Status) -> Self {
29        Response { status, headers: Headers::new(), body: Vec::new(), upgrade: None }
30    }
31
32    /// Answer `101` and hand the connection to another protocol.
33    ///
34    /// The caller sets whatever headers the new protocol's handshake requires;
35    /// this only arranges for the socket to be handed over afterwards.
36    pub fn upgrading(mut self, upgrade: impl crate::upgrade::Upgrade) -> Self {
37        self.status = Status(101);
38        self.upgrade = Some(std::sync::Arc::new(upgrade));
39        self
40    }
41
42    /// Whether this response takes the connection over.
43    pub fn upgrades(&self) -> bool {
44        self.upgrade.is_some()
45    }
46
47    /// Take the upgrade out of a dispatched response.
48    ///
49    /// Public so a test can drive an upgrade through the router rather than
50    /// only over a real socket.
51    pub fn take_upgrade(&mut self) -> Option<crate::upgrade::Upgrader> {
52        self.upgrade.take()
53    }
54
55    pub fn ok() -> Self {
56        Response::new(Status::OK)
57    }
58
59    pub fn no_content() -> Self {
60        Response::new(Status::NO_CONTENT)
61    }
62
63    pub fn not_found() -> Self {
64        Response::new(Status::NOT_FOUND).with_html("<h1>404 Not Found</h1>")
65    }
66
67    /// A `302` redirect. Use [`Response::see_other`] after a form submission so
68    /// the browser switches to GET.
69    pub fn redirect(location: impl Into<String>) -> Self {
70        Response::new(Status::FOUND).with_header("location", location)
71    }
72
73    pub fn see_other(location: impl Into<String>) -> Self {
74        Response::new(Status::SEE_OTHER).with_header("location", location)
75    }
76
77    pub fn json(value: impl Into<Json>) -> Self {
78        Response::ok().with_json(value)
79    }
80
81    pub fn html(body: impl Into<String>) -> Self {
82        Response::ok().with_html(body)
83    }
84
85    pub fn text(body: impl Into<String>) -> Self {
86        Response::ok().with_text(body)
87    }
88
89    pub fn with_status(mut self, status: impl Into<Status>) -> Self {
90        self.status = status.into();
91        self
92    }
93
94    pub fn with_header(mut self, name: &str, value: impl Into<String>) -> Self {
95        self.headers.set(name, value);
96        self
97    }
98
99    pub fn with_body(mut self, body: impl Into<Vec<u8>>) -> Self {
100        self.body = body.into();
101        self
102    }
103
104    pub fn with_json(self, value: impl Into<Json>) -> Self {
105        self.with_header("content-type", "application/json; charset=utf-8")
106            .with_body(value.into().to_string())
107    }
108
109    pub fn with_html(self, body: impl Into<String>) -> Self {
110        self.with_header("content-type", "text/html; charset=utf-8").with_body(body.into())
111    }
112
113    pub fn with_text(self, body: impl Into<String>) -> Self {
114        self.with_header("content-type", "text/plain; charset=utf-8").with_body(body.into())
115    }
116
117    pub fn with_cookie(mut self, cookie: Cookie) -> Self {
118        self.headers.append("set-cookie", cookie.to_header());
119        self
120    }
121
122    /// Expire a cookie on the client.
123    pub fn without_cookie(self, name: &str) -> Self {
124        self.with_cookie(Cookie::forget(name))
125    }
126
127    pub fn body_string(&self) -> String {
128        String::from_utf8_lossy(&self.body).into_owned()
129    }
130
131    /// Serialize into an HTTP/1.1 wire response.
132    ///
133    /// `include_body` is false for HEAD requests, which must report the length
134    /// they would have sent while sending nothing.
135    pub fn to_bytes(&self, include_body: bool) -> Vec<u8> {
136        let bodyless = self.status.is_bodyless();
137        let body: &[u8] = if bodyless { &[] } else { &self.body };
138
139        let mut head = format!("HTTP/1.1 {} {}\r\n", self.status.code(), self.status.reason());
140        for (name, value) in self.headers.iter() {
141            if name == "content-length" {
142                continue;
143            }
144            head.push_str(&format!("{name}: {value}\r\n"));
145        }
146        if !bodyless {
147            head.push_str(&format!("content-length: {}\r\n", body.len()));
148        }
149        head.push_str("\r\n");
150
151        let mut out = head.into_bytes();
152        if include_body && !bodyless {
153            out.extend_from_slice(body);
154        }
155        out
156    }
157}
158
159impl Default for Response {
160    fn default() -> Self {
161        Response::ok()
162    }
163}
164
165/// Anything a handler is allowed to return.
166///
167/// This is what lets a handler return a `&str`, a `Json`, a `Result`, or a full
168/// `Response` without wrapping it by hand.
169pub trait IntoResponse {
170    fn into_response(self) -> Response;
171}
172
173impl IntoResponse for Response {
174    fn into_response(self) -> Response {
175        self
176    }
177}
178
179impl IntoResponse for Status {
180    fn into_response(self) -> Response {
181        Response::new(self)
182    }
183}
184
185impl IntoResponse for String {
186    fn into_response(self) -> Response {
187        Response::html(self)
188    }
189}
190
191impl IntoResponse for &str {
192    fn into_response(self) -> Response {
193        Response::html(self.to_string())
194    }
195}
196
197impl IntoResponse for Json {
198    fn into_response(self) -> Response {
199        Response::json(self)
200    }
201}
202
203impl IntoResponse for () {
204    fn into_response(self) -> Response {
205        Response::no_content()
206    }
207}
208
209impl<T: IntoResponse> IntoResponse for (u16, T) {
210    fn into_response(self) -> Response {
211        let (status, inner) = self;
212        inner.into_response().with_status(status)
213    }
214}
215
216/// `None` becomes a 404, which makes `req.param_as::<i64>("id")?` style
217/// lookups read naturally in a handler.
218impl<T: IntoResponse> IntoResponse for Option<T> {
219    fn into_response(self) -> Response {
220        match self {
221            Some(value) => value.into_response(),
222            None => Response::not_found(),
223        }
224    }
225}
226
227/// A framework error renders as the development error page, or a generic 500
228/// in production.
229impl IntoResponse for Error {
230    fn into_response(self) -> Response {
231        crate::error_page::response_for(&self)
232    }
233}
234
235/// `?` in a handler works for any error that knows how to become a response.
236///
237/// This is what lets validation return a 422 with its own JSON body while a
238/// framework error still reaches the error page: each error type decides how it
239/// is rendered, rather than everything collapsing into a 500.
240impl<T: IntoResponse, E: IntoResponse> IntoResponse for Result<T, E> {
241    fn into_response(self) -> Response {
242        match self {
243            Ok(value) => value.into_response(),
244            Err(error) => error.into_response(),
245        }
246    }
247}
248
249/// An I/O failure in a handler is a server error; carried separately because
250/// `std::io::Error` cannot implement a foreign trait here.
251impl IntoResponse for std::io::Error {
252    fn into_response(self) -> Response {
253        crate::error_page::response_for(&Error::Io(self))
254    }
255}
256
257#[cfg(test)]
258mod tests {
259    use super::*;
260
261    #[test]
262    fn serializes_a_wire_response() {
263        let response = Response::json(Json::object([("ok", true.into())]));
264        let wire = String::from_utf8(response.to_bytes(true)).unwrap();
265
266        assert!(wire.starts_with("HTTP/1.1 200 OK\r\n"));
267        assert!(wire.contains("content-type: application/json; charset=utf-8\r\n"));
268        assert!(wire.contains("content-length: 11\r\n"));
269        assert!(wire.ends_with("\r\n\r\n{\"ok\":true}"));
270    }
271
272    #[test]
273    fn head_requests_keep_the_length_but_drop_the_body() {
274        let response = Response::text("hello");
275        let wire = String::from_utf8(response.to_bytes(false)).unwrap();
276
277        assert!(wire.contains("content-length: 5\r\n"));
278        assert!(wire.ends_with("\r\n\r\n"));
279    }
280
281    #[test]
282    fn bodyless_statuses_send_no_content_length() {
283        let wire = String::from_utf8(Response::no_content().to_bytes(true)).unwrap();
284        assert!(!wire.contains("content-length"));
285    }
286
287    #[test]
288    fn repeated_cookies_each_get_their_own_header() {
289        let response = Response::ok()
290            .with_cookie(Cookie::new("a", "1"))
291            .with_cookie(Cookie::new("b", "2"));
292        let wire = String::from_utf8(response.to_bytes(true)).unwrap();
293
294        assert_eq!(wire.matches("set-cookie:").count(), 2);
295    }
296
297    #[test]
298    fn common_return_types_convert() {
299        assert_eq!("hi".into_response().status, Status::OK);
300        assert_eq!(().into_response().status, Status::NO_CONTENT);
301        assert_eq!(Option::<String>::None.into_response().status, Status::NOT_FOUND);
302        assert_eq!((201, "made").into_response().status, Status::CREATED);
303
304        let failed: Result<&str, Error> = Err(Error::msg("boom"));
305        assert!(failed.into_response().status.is_error());
306    }
307}