Skip to main content

actix_web/response/
response.rs

1use std::{
2    cell::{Ref, RefMut},
3    fmt,
4};
5
6use actix_http::{
7    body::{BoxBody, EitherBody, MessageBody},
8    header::HeaderMap,
9    Extensions, Response, ResponseHead, StatusCode,
10};
11#[cfg(any(feature = "cookies", feature = "cookies-0_18"))]
12use actix_http::{
13    error::HttpError,
14    header::{self, HeaderValue},
15};
16#[cfg(feature = "cookies")]
17use cookie::Cookie;
18#[cfg(all(feature = "cookies-0_18", not(feature = "cookies")))]
19use cookie_0_18::Cookie;
20
21use crate::{error::Error, HttpRequest, HttpResponseBuilder, Responder};
22
23/// An outgoing response.
24pub struct HttpResponse<B = BoxBody> {
25    res: Response<B>,
26    error: Option<Error>,
27}
28
29impl HttpResponse<BoxBody> {
30    /// Constructs a response.
31    #[inline]
32    pub fn new(status: StatusCode) -> Self {
33        Self {
34            res: Response::new(status),
35            error: None,
36        }
37    }
38
39    /// Constructs a response builder with specific HTTP status.
40    #[inline]
41    pub fn build(status: StatusCode) -> HttpResponseBuilder {
42        HttpResponseBuilder::new(status)
43    }
44
45    /// Create an error response.
46    #[inline]
47    pub fn from_error(error: impl Into<Error>) -> Self {
48        let error = error.into();
49        let mut response = error.as_response_error().error_response();
50        response.error = Some(error);
51        response
52    }
53}
54
55impl<B> HttpResponse<B> {
56    /// Constructs a response with body
57    #[inline]
58    pub fn with_body(status: StatusCode, body: B) -> Self {
59        Self {
60            res: Response::with_body(status, body),
61            error: None,
62        }
63    }
64
65    /// Returns a reference to response head.
66    #[inline]
67    pub fn head(&self) -> &ResponseHead {
68        self.res.head()
69    }
70
71    /// Returns a mutable reference to response head.
72    #[inline]
73    pub fn head_mut(&mut self) -> &mut ResponseHead {
74        self.res.head_mut()
75    }
76
77    /// The source `error` for this response
78    #[inline]
79    pub fn error(&self) -> Option<&Error> {
80        self.error.as_ref()
81    }
82
83    /// Get the response status code
84    #[inline]
85    pub fn status(&self) -> StatusCode {
86        self.res.status()
87    }
88
89    /// Set the `StatusCode` for this response
90    #[inline]
91    pub fn status_mut(&mut self) -> &mut StatusCode {
92        self.res.status_mut()
93    }
94
95    /// Get the headers from the response
96    #[inline]
97    pub fn headers(&self) -> &HeaderMap {
98        self.res.headers()
99    }
100
101    /// Get a mutable reference to the headers
102    #[inline]
103    pub fn headers_mut(&mut self) -> &mut HeaderMap {
104        self.res.headers_mut()
105    }
106
107    /// Iterates over the response cookies that cookie (v0.18) can parse.
108    #[cfg(feature = "cookies-0_18")]
109    pub fn cookies_0_18(&self) -> impl Iterator<Item = cookie_0_18::Cookie<'_>> {
110        self.headers()
111            .get_all(header::SET_COOKIE)
112            .filter_map(|header| cookie_0_18::Cookie::parse_encoded(header.to_str().ok()?).ok())
113    }
114
115    /// Appends a cookie (v0.18) Set-Cookie header.
116    #[cfg(feature = "cookies-0_18")]
117    pub fn add_cookie_0_18(&mut self, cookie: &cookie_0_18::Cookie<'_>) -> Result<(), HttpError> {
118        let value = HeaderValue::from_str(&cookie.to_string())?;
119        self.headers_mut().append(header::SET_COOKIE, value);
120        Ok(())
121    }
122
123    /// Appends a removal cookie with the given name, path, and domain using cookie (v0.18).
124    #[cfg(feature = "cookies-0_18")]
125    pub fn add_removal_cookie_0_18(
126        &mut self,
127        cookie: &cookie_0_18::Cookie<'_>,
128    ) -> Result<(), HttpError> {
129        let mut cookie = cookie.clone();
130        cookie.make_removal();
131        self.add_cookie_0_18(&cookie)
132    }
133
134    /// Get an iterator for the cookies set by this response.
135    #[cfg(feature = "cookies")]
136    pub fn cookies(&self) -> CookieIter<'_> {
137        CookieIter {
138            iter: self.headers().get_all(header::SET_COOKIE),
139        }
140    }
141
142    /// Add a cookie to this response.
143    ///
144    /// # Errors
145    /// Returns an error if the cookie results in a malformed `Set-Cookie` header.
146    #[cfg(feature = "cookies")]
147    pub fn add_cookie(&mut self, cookie: &Cookie<'_>) -> Result<(), HttpError> {
148        HeaderValue::from_str(&cookie.to_string())
149            .map(|cookie| self.headers_mut().append(header::SET_COOKIE, cookie))
150            .map_err(Into::into)
151    }
152
153    /// Add a "removal" cookie to the response that matches attributes of given cookie.
154    ///
155    /// This will cause browsers/clients to remove stored cookies with this name.
156    ///
157    /// The `Set-Cookie` header added to the response will have:
158    /// - name matching given cookie;
159    /// - domain matching given cookie;
160    /// - path matching given cookie;
161    /// - an empty value;
162    /// - a max-age of `0`;
163    /// - an expiration date far in the past.
164    ///
165    /// If the cookie you're trying to remove has an explicit path or domain set, those attributes
166    /// will need to be included in the cookie passed in here.
167    ///
168    /// # Errors
169    /// Returns an error if the given name results in a malformed `Set-Cookie` header.
170    #[cfg(feature = "cookies")]
171    pub fn add_removal_cookie(&mut self, cookie: &Cookie<'_>) -> Result<(), HttpError> {
172        let mut removal_cookie = cookie.to_owned();
173        removal_cookie.make_removal();
174
175        HeaderValue::from_str(&removal_cookie.to_string())
176            .map(|cookie| self.headers_mut().append(header::SET_COOKIE, cookie))
177            .map_err(Into::into)
178    }
179
180    /// Removes all `Set-Cookie` headers for cookies with the given name.
181    ///
182    /// Returns the number of cookies removed.
183    ///
184    /// To remove a cookie stored by the client, send a removal cookie.
185    ///
186    #[cfg(any(feature = "cookies", feature = "cookies-0_18"))]
187    #[cfg_attr(
188        feature = "cookies",
189        doc = "- For cookie (v0.16), use [`add_removal_cookie()`](Self::add_removal_cookie)."
190    )]
191    #[cfg_attr(
192        feature = "cookies-0_18",
193        doc = "- For cookie (v0.18), use [`add_removal_cookie_0_18()`](Self::add_removal_cookie_0_18)."
194    )]
195    pub fn del_cookie(&mut self, name: &str) -> usize {
196        let headers = self.headers_mut();
197
198        let vals = headers
199            .get_all(header::SET_COOKIE)
200            .map(|v| v.to_owned())
201            .collect::<Vec<_>>();
202
203        headers.remove(header::SET_COOKIE);
204
205        let mut count: usize = 0;
206
207        for v in vals {
208            if let Ok(s) = v.to_str() {
209                if let Ok(c) = Cookie::parse_encoded(s) {
210                    if c.name() == name {
211                        count += 1;
212                        continue;
213                    }
214                }
215            }
216
217            // put set-cookie header head back if it does not validate
218            headers.append(header::SET_COOKIE, v);
219        }
220
221        count
222    }
223
224    /// Connection upgrade status
225    #[inline]
226    pub fn upgrade(&self) -> bool {
227        self.res.upgrade()
228    }
229
230    /// Keep-alive status for this connection
231    pub fn keep_alive(&self) -> bool {
232        self.res.keep_alive()
233    }
234
235    /// Returns reference to the response-local data/extensions container.
236    #[inline]
237    pub fn extensions(&self) -> Ref<'_, Extensions> {
238        self.res.extensions()
239    }
240
241    /// Returns reference to the response-local data/extensions container.
242    #[inline]
243    pub fn extensions_mut(&mut self) -> RefMut<'_, Extensions> {
244        self.res.extensions_mut()
245    }
246
247    /// Returns a reference to this response's body.
248    #[inline]
249    pub fn body(&self) -> &B {
250        self.res.body()
251    }
252
253    /// Sets new body.
254    pub fn set_body<B2>(self, body: B2) -> HttpResponse<B2> {
255        HttpResponse {
256            res: self.res.set_body(body),
257            error: self.error,
258        }
259    }
260
261    /// Returns split head and body.
262    ///
263    /// # Implementation Notes
264    /// Due to internal performance optimizations, the first element of the returned tuple is an
265    /// `HttpResponse` as well but only contains the head of the response this was called on.
266    pub fn into_parts(self) -> (HttpResponse<()>, B) {
267        let (head, body) = self.res.into_parts();
268
269        (
270            HttpResponse {
271                res: head,
272                error: self.error,
273            },
274            body,
275        )
276    }
277
278    /// Drops body and returns new response.
279    pub fn drop_body(self) -> HttpResponse<()> {
280        HttpResponse {
281            res: self.res.drop_body(),
282            error: self.error,
283        }
284    }
285
286    /// Map the current body type to another using a closure, returning a new response.
287    ///
288    /// Closure receives the response head and the current body type.
289    pub fn map_body<F, B2>(self, f: F) -> HttpResponse<B2>
290    where
291        F: FnOnce(&mut ResponseHead, B) -> B2,
292    {
293        HttpResponse {
294            res: self.res.map_body(f),
295            error: self.error,
296        }
297    }
298
299    /// Map the current body type `B` to `EitherBody::Left(B)`.
300    ///
301    /// Useful for middleware which can generate their own responses.
302    #[inline]
303    pub fn map_into_left_body<R>(self) -> HttpResponse<EitherBody<B, R>> {
304        self.map_body(|_, body| EitherBody::left(body))
305    }
306
307    /// Map the current body type `B` to `EitherBody::Right(B)`.
308    ///
309    /// Useful for middleware which can generate their own responses.
310    #[inline]
311    pub fn map_into_right_body<L>(self) -> HttpResponse<EitherBody<L, B>> {
312        self.map_body(|_, body| EitherBody::right(body))
313    }
314
315    /// Map the current body to a type-erased `BoxBody`.
316    #[inline]
317    pub fn map_into_boxed_body(self) -> HttpResponse<BoxBody>
318    where
319        B: MessageBody + 'static,
320    {
321        self.map_body(|_, body| body.boxed())
322    }
323
324    /// Returns the response body, dropping all other parts.
325    pub fn into_body(self) -> B {
326        self.res.into_body()
327    }
328}
329
330impl<B> fmt::Debug for HttpResponse<B>
331where
332    B: MessageBody,
333{
334    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
335        f.debug_struct("HttpResponse")
336            .field("error", &self.error)
337            .field("res", &self.res)
338            .finish()
339    }
340}
341
342impl<B> From<Response<B>> for HttpResponse<B> {
343    fn from(res: Response<B>) -> Self {
344        HttpResponse { res, error: None }
345    }
346}
347
348impl From<Error> for HttpResponse {
349    fn from(err: Error) -> Self {
350        HttpResponse::from_error(err)
351    }
352}
353
354impl<B> From<HttpResponse<B>> for Response<B> {
355    fn from(res: HttpResponse<B>) -> Self {
356        // this impl will always be called as part of dispatcher
357        res.res
358    }
359}
360
361// Rationale for cfg(test): this impl causes false positives on a clippy lint (async_yields_async)
362// when returning an HttpResponse from an async function/closure and it's not very useful outside of
363// tests anyway.
364#[cfg(test)]
365mod response_fut_impl {
366    use std::{
367        future::Future,
368        mem,
369        pin::Pin,
370        task::{Context, Poll},
371    };
372
373    use super::*;
374
375    // Future is only implemented for BoxBody payload type because it's the most useful for making
376    // simple handlers without async blocks. Making it generic over all MessageBody types requires a
377    // future impl on Response which would cause its body field to be, undesirably, Option<B>.
378    //
379    // This impl is not particularly efficient due to the Response construction and should probably
380    // not be invoked if performance is important. Prefer an async fn/block in such cases.
381    impl Future for HttpResponse<BoxBody> {
382        type Output = Result<Response<BoxBody>, Error>;
383
384        fn poll(mut self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Self::Output> {
385            if let Some(err) = self.error.take() {
386                return Poll::Ready(Err(err));
387            }
388
389            Poll::Ready(Ok(mem::replace(
390                &mut self.res,
391                Response::new(StatusCode::default()),
392            )))
393        }
394    }
395}
396
397impl<B> Responder for HttpResponse<B>
398where
399    B: MessageBody + 'static,
400{
401    type Body = B;
402
403    #[inline]
404    fn respond_to(self, _: &HttpRequest) -> HttpResponse<Self::Body> {
405        self
406    }
407}
408
409#[cfg(feature = "cookies")]
410pub struct CookieIter<'a> {
411    iter: std::slice::Iter<'a, HeaderValue>,
412}
413
414#[cfg(feature = "cookies")]
415impl<'a> Iterator for CookieIter<'a> {
416    type Item = Cookie<'a>;
417
418    #[inline]
419    fn next(&mut self) -> Option<Cookie<'a>> {
420        for v in self.iter.by_ref() {
421            if let Ok(c) = Cookie::parse_encoded(v.to_str().ok()?) {
422                return Some(c);
423            }
424        }
425        None
426    }
427}
428
429#[cfg(test)]
430mod tests {
431    use static_assertions::assert_impl_all;
432
433    use super::*;
434    use crate::http::header::COOKIE;
435
436    assert_impl_all!(HttpResponse: Responder);
437    assert_impl_all!(HttpResponse<String>: Responder);
438    assert_impl_all!(HttpResponse<&'static str>: Responder);
439    assert_impl_all!(HttpResponse<crate::body::None>: Responder);
440
441    #[test]
442    fn test_debug() {
443        let resp = HttpResponse::Ok()
444            .append_header((COOKIE, HeaderValue::from_static("cookie1=value1; ")))
445            .append_header((COOKIE, HeaderValue::from_static("cookie2=value2; ")))
446            .finish();
447        let dbg = format!("{:?}", resp);
448        assert!(dbg.contains("HttpResponse"));
449    }
450}
451
452#[cfg(test)]
453#[cfg(feature = "cookies")]
454mod cookie_tests {
455    use super::*;
456
457    #[test]
458    fn removal_cookies() {
459        let mut res = HttpResponse::Ok().finish();
460        let cookie = Cookie::new("foo", "");
461        res.add_removal_cookie(&cookie).unwrap();
462        let set_cookie_hdr = res.headers().get(header::SET_COOKIE).unwrap();
463        assert_eq!(
464            &set_cookie_hdr.as_bytes()[..25],
465            &b"foo=; Max-Age=0; Expires="[..],
466            "unexpected set-cookie value: {:?}",
467            set_cookie_hdr.to_str()
468        );
469    }
470}