Skip to main content

actix_web/response/
builder.rs

1use std::{
2    cell::{Ref, RefMut},
3    future::Future,
4    pin::Pin,
5    task::{Context, Poll},
6};
7
8use actix_http::{error::HttpError, Response, ResponseHead};
9use bytes::Bytes;
10use futures_core::Stream;
11use serde::Serialize;
12
13use crate::{
14    body::{BodyStream, BoxBody, MessageBody, SizedStream},
15    dev::Extensions,
16    error::{Error, JsonPayloadError},
17    http::{
18        header::{self, HeaderName, TryIntoHeaderPair, TryIntoHeaderValue},
19        ConnectionType, StatusCode,
20    },
21    BoxError, HttpRequest, HttpResponse, Responder,
22};
23
24/// An HTTP response builder.
25///
26/// This type can be used to construct an instance of `Response` through a builder-like pattern.
27pub struct HttpResponseBuilder {
28    res: Option<Response<BoxBody>>,
29    error: Option<HttpError>,
30}
31
32impl HttpResponseBuilder {
33    #[inline]
34    /// Create response builder
35    pub fn new(status: StatusCode) -> Self {
36        Self {
37            res: Some(Response::with_body(status, BoxBody::new(()))),
38            error: None,
39        }
40    }
41
42    /// Set HTTP status code of this response.
43    #[inline]
44    pub fn status(&mut self, status: StatusCode) -> &mut Self {
45        if let Some(parts) = self.inner() {
46            parts.status = status;
47        }
48        self
49    }
50
51    /// Insert a header, replacing any that were set with an equivalent field name.
52    ///
53    /// ```
54    /// use actix_web::{HttpResponse, http::header};
55    ///
56    /// HttpResponse::Ok()
57    ///     .insert_header(header::ContentType(mime::APPLICATION_JSON))
58    ///     .insert_header(("X-TEST", "value"))
59    ///     .finish();
60    /// ```
61    pub fn insert_header(&mut self, header: impl TryIntoHeaderPair) -> &mut Self {
62        if let Some(parts) = self.inner() {
63            match header.try_into_pair() {
64                Ok((key, value)) => {
65                    parts.headers.insert(key, value);
66                }
67                Err(err) => self.error = Some(err.into()),
68            };
69        }
70
71        self
72    }
73
74    /// Append a header, keeping any that were set with an equivalent field name.
75    ///
76    /// ```
77    /// use actix_web::{HttpResponse, http::header};
78    ///
79    /// HttpResponse::Ok()
80    ///     .append_header(header::ContentType(mime::APPLICATION_JSON))
81    ///     .append_header(("X-TEST", "value1"))
82    ///     .append_header(("X-TEST", "value2"))
83    ///     .finish();
84    /// ```
85    pub fn append_header(&mut self, header: impl TryIntoHeaderPair) -> &mut Self {
86        if let Some(parts) = self.inner() {
87            match header.try_into_pair() {
88                Ok((key, value)) => parts.headers.append(key, value),
89                Err(err) => self.error = Some(err.into()),
90            };
91        }
92
93        self
94    }
95
96    /// Replaced with [`Self::insert_header()`].
97    #[doc(hidden)]
98    #[deprecated(
99        since = "4.0.0",
100        note = "Replaced with `insert_header((key, value))`. Will be removed in v5."
101    )]
102    pub fn set_header<K, V>(&mut self, key: K, value: V) -> &mut Self
103    where
104        K: TryInto<HeaderName>,
105        K::Error: Into<HttpError>,
106        V: TryIntoHeaderValue,
107    {
108        if self.error.is_some() {
109            return self;
110        }
111
112        match (key.try_into(), value.try_into_value()) {
113            (Ok(name), Ok(value)) => return self.insert_header((name, value)),
114            (Err(err), _) => self.error = Some(err.into()),
115            (_, Err(err)) => self.error = Some(err.into()),
116        }
117
118        self
119    }
120
121    /// Replaced with [`Self::append_header()`].
122    #[doc(hidden)]
123    #[deprecated(
124        since = "4.0.0",
125        note = "Replaced with `append_header((key, value))`. Will be removed in v5."
126    )]
127    pub fn header<K, V>(&mut self, key: K, value: V) -> &mut Self
128    where
129        K: TryInto<HeaderName>,
130        K::Error: Into<HttpError>,
131        V: TryIntoHeaderValue,
132    {
133        if self.error.is_some() {
134            return self;
135        }
136
137        match (key.try_into(), value.try_into_value()) {
138            (Ok(name), Ok(value)) => return self.append_header((name, value)),
139            (Err(err), _) => self.error = Some(err.into()),
140            (_, Err(err)) => self.error = Some(err.into()),
141        }
142
143        self
144    }
145
146    /// Set the custom reason for the response.
147    #[inline]
148    pub fn reason(&mut self, reason: &'static str) -> &mut Self {
149        if let Some(parts) = self.inner() {
150            parts.reason = Some(reason);
151        }
152        self
153    }
154
155    /// Set connection type to KeepAlive
156    #[inline]
157    pub fn keep_alive(&mut self) -> &mut Self {
158        if let Some(parts) = self.inner() {
159            parts.set_connection_type(ConnectionType::KeepAlive);
160        }
161        self
162    }
163
164    /// Set connection type to Upgrade
165    #[inline]
166    pub fn upgrade<V>(&mut self, value: V) -> &mut Self
167    where
168        V: TryIntoHeaderValue,
169    {
170        if let Some(parts) = self.inner() {
171            parts.set_connection_type(ConnectionType::Upgrade);
172        }
173
174        if let Ok(value) = value.try_into_value() {
175            self.insert_header((header::UPGRADE, value));
176        }
177
178        self
179    }
180
181    /// Force close connection, even if it is marked as keep-alive
182    #[inline]
183    pub fn force_close(&mut self) -> &mut Self {
184        if let Some(parts) = self.inner() {
185            parts.set_connection_type(ConnectionType::Close);
186        }
187        self
188    }
189
190    /// Disable chunked transfer encoding for HTTP/1.1 streaming responses.
191    #[inline]
192    pub fn no_chunking(&mut self, len: u64) -> &mut Self {
193        let mut buf = itoa::Buffer::new();
194        self.insert_header((header::CONTENT_LENGTH, buf.format(len)));
195
196        if let Some(parts) = self.inner() {
197            parts.no_chunking(true);
198        }
199        self
200    }
201
202    /// Set response content type.
203    #[inline]
204    pub fn content_type<V>(&mut self, value: V) -> &mut Self
205    where
206        V: TryIntoHeaderValue,
207    {
208        if let Some(parts) = self.inner() {
209            match value.try_into_value() {
210                Ok(value) => {
211                    parts.headers.insert(header::CONTENT_TYPE, value);
212                }
213                Err(err) => self.error = Some(err.into()),
214            };
215        }
216        self
217    }
218
219    /// Add a cookie to the response.
220    ///
221    /// To send a "removal" cookie, call [`.make_removal()`](cookie::Cookie::make_removal) on the
222    /// given cookie. See [`HttpResponse::add_removal_cookie()`] to learn more.
223    ///
224    /// # Examples
225    /// Send a new cookie:
226    /// ```
227    /// use actix_web::{HttpResponse, cookie::Cookie};
228    ///
229    /// let res = HttpResponse::Ok()
230    ///     .cookie(
231    ///         Cookie::build("name", "value")
232    ///             .domain("www.rust-lang.org")
233    ///             .path("/")
234    ///             .secure(true)
235    ///             .http_only(true)
236    ///             .finish(),
237    ///     )
238    ///     .finish();
239    /// ```
240    ///
241    /// Send a removal cookie:
242    /// ```
243    /// use actix_web::{HttpResponse, cookie::Cookie};
244    ///
245    /// // the name, domain and path match the cookie created in the previous example
246    /// let mut cookie = Cookie::build("name", "value-does-not-matter")
247    ///     .domain("www.rust-lang.org")
248    ///     .path("/")
249    ///     .finish();
250    /// cookie.make_removal();
251    ///
252    /// let res = HttpResponse::Ok()
253    ///     .cookie(cookie)
254    ///     .finish();
255    /// ```
256    #[cfg(feature = "cookies")]
257    pub fn cookie(&mut self, cookie: cookie::Cookie<'_>) -> &mut Self {
258        match cookie.to_string().try_into_value() {
259            Ok(hdr_val) => self.append_header((header::SET_COOKIE, hdr_val)),
260            Err(err) => {
261                self.error = Some(err.into());
262                self
263            }
264        }
265    }
266
267    /// Appends a cookie (v0.18) Set-Cookie header.
268    #[cfg(feature = "cookies-0_18")]
269    pub fn cookie_0_18(&mut self, cookie: cookie_0_18::Cookie<'_>) -> &mut Self {
270        self.append_header((header::SET_COOKIE, cookie.to_string()))
271    }
272
273    /// Returns a reference to the response-local data/extensions container.
274    #[inline]
275    pub fn extensions(&self) -> Ref<'_, Extensions> {
276        self.res
277            .as_ref()
278            .expect("Cannot reuse response builder")
279            .extensions()
280    }
281
282    /// Returns a mutable reference to the response-local data/extensions container.
283    #[inline]
284    pub fn extensions_mut(&mut self) -> RefMut<'_, Extensions> {
285        self.res
286            .as_mut()
287            .expect("Cannot reuse response builder")
288            .extensions_mut()
289    }
290
291    /// Set a body and build the `HttpResponse`.
292    ///
293    /// Unlike [`message_body`](Self::message_body), errors are converted into error
294    /// responses immediately.
295    ///
296    /// `HttpResponseBuilder` can not be used after this call.
297    pub fn body<B>(&mut self, body: B) -> HttpResponse<BoxBody>
298    where
299        B: MessageBody + 'static,
300    {
301        match self.message_body(body) {
302            Ok(res) => res.map_into_boxed_body(),
303            Err(err) => HttpResponse::from_error(err),
304        }
305    }
306
307    /// Set a body and build the `HttpResponse`.
308    ///
309    /// `HttpResponseBuilder` can not be used after this call.
310    pub fn message_body<B>(&mut self, body: B) -> Result<HttpResponse<B>, Error> {
311        if let Some(err) = self.error.take() {
312            return Err(err.into());
313        }
314
315        let res = self
316            .res
317            .take()
318            .expect("Cannot reuse response builder")
319            .set_body(body);
320
321        Ok(HttpResponse::from(res))
322    }
323
324    /// Set a streaming body and build the `HttpResponse`.
325    ///
326    /// `HttpResponseBuilder` can not be used after this call.
327    ///
328    /// If `Content-Type` is not set, then it is automatically set to `application/octet-stream`.
329    ///
330    /// If `Content-Length` is set, then [`no_chunking()`](Self::no_chunking) is automatically called.
331    #[inline]
332    pub fn streaming<S, E>(&mut self, stream: S) -> HttpResponse
333    where
334        S: Stream<Item = Result<Bytes, E>> + 'static,
335        E: Into<BoxError> + 'static,
336    {
337        // Set mime type to application/octet-stream if it is not set
338        if let Some(parts) = self.inner() {
339            if !parts.headers.contains_key(header::CONTENT_TYPE) {
340                self.insert_header((header::CONTENT_TYPE, mime::APPLICATION_OCTET_STREAM));
341            }
342        }
343
344        let content_length = self
345            .inner()
346            .and_then(|parts| parts.headers.get(header::CONTENT_LENGTH))
347            .and_then(|value| value.to_str().ok())
348            .and_then(|value| value.parse::<u64>().ok());
349
350        if let Some(len) = content_length {
351            self.no_chunking(len);
352            self.body(SizedStream::new(len, stream))
353        } else {
354            self.body(BodyStream::new(stream))
355        }
356    }
357
358    /// Set a JSON body and build the `HttpResponse`.
359    ///
360    /// `HttpResponseBuilder` can not be used after this call.
361    pub fn json(&mut self, value: impl Serialize) -> HttpResponse {
362        match serde_json::to_string(&value) {
363            Ok(body) => {
364                let contains = if let Some(parts) = self.inner() {
365                    parts.headers.contains_key(header::CONTENT_TYPE)
366                } else {
367                    true
368                };
369
370                if !contains {
371                    self.insert_header((header::CONTENT_TYPE, mime::APPLICATION_JSON));
372                }
373
374                self.body(body)
375            }
376            Err(err) => HttpResponse::from_error(JsonPayloadError::Serialize(err)),
377        }
378    }
379
380    /// Set an empty body and build the `HttpResponse`.
381    ///
382    /// `HttpResponseBuilder` can not be used after this call.
383    #[inline]
384    pub fn finish(&mut self) -> HttpResponse {
385        self.body(())
386    }
387
388    /// This method construct new `HttpResponseBuilder`
389    pub fn take(&mut self) -> Self {
390        Self {
391            res: self.res.take(),
392            error: self.error.take(),
393        }
394    }
395
396    fn inner(&mut self) -> Option<&mut ResponseHead> {
397        if self.error.is_some() {
398            return None;
399        }
400
401        self.res.as_mut().map(Response::head_mut)
402    }
403}
404
405impl From<HttpResponseBuilder> for HttpResponse {
406    fn from(mut builder: HttpResponseBuilder) -> Self {
407        builder.finish()
408    }
409}
410
411impl From<HttpResponseBuilder> for Response<BoxBody> {
412    fn from(mut builder: HttpResponseBuilder) -> Self {
413        builder.finish().into()
414    }
415}
416
417impl Future for HttpResponseBuilder {
418    type Output = Result<HttpResponse, Error>;
419
420    fn poll(mut self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Self::Output> {
421        Poll::Ready(Ok(self.finish()))
422    }
423}
424
425impl Responder for HttpResponseBuilder {
426    type Body = BoxBody;
427
428    #[inline]
429    fn respond_to(mut self, _: &HttpRequest) -> HttpResponse<Self::Body> {
430        self.finish()
431    }
432}
433
434#[cfg(test)]
435mod tests {
436    use super::*;
437    use crate::{
438        body,
439        http::header::{HeaderValue, CONTENT_TYPE},
440        test::assert_body_eq,
441    };
442
443    #[test]
444    fn test_basic_builder() {
445        let resp = HttpResponse::Ok()
446            .insert_header(("X-TEST", "value"))
447            .finish();
448        assert_eq!(resp.status(), StatusCode::OK);
449    }
450
451    #[test]
452    fn test_upgrade() {
453        let resp = HttpResponseBuilder::new(StatusCode::OK)
454            .upgrade("websocket")
455            .finish();
456        assert!(resp.upgrade());
457        assert_eq!(
458            resp.headers().get(header::UPGRADE).unwrap(),
459            HeaderValue::from_static("websocket")
460        );
461    }
462
463    #[test]
464    fn test_force_close() {
465        let resp = HttpResponseBuilder::new(StatusCode::OK)
466            .force_close()
467            .finish();
468        assert!(!resp.keep_alive())
469    }
470
471    #[test]
472    fn test_content_type() {
473        let resp = HttpResponseBuilder::new(StatusCode::OK)
474            .content_type("text/plain")
475            .body(Bytes::new());
476        assert_eq!(resp.headers().get(CONTENT_TYPE).unwrap(), "text/plain")
477    }
478
479    #[tokio::test(flavor = "local")]
480    async fn test_json() {
481        let res = HttpResponse::Ok().json(vec!["v1", "v2", "v3"]);
482        let ct = res.headers().get(CONTENT_TYPE).unwrap();
483        assert_eq!(ct, HeaderValue::from_static("application/json"));
484        assert_body_eq!(res, br#"["v1","v2","v3"]"#);
485
486        let res = HttpResponse::Ok().json(["v1", "v2", "v3"]);
487        let ct = res.headers().get(CONTENT_TYPE).unwrap();
488        assert_eq!(ct, HeaderValue::from_static("application/json"));
489        assert_body_eq!(res, br#"["v1","v2","v3"]"#);
490
491        // content type override
492        let res = HttpResponse::Ok()
493            .insert_header((CONTENT_TYPE, "text/json"))
494            .json(["v1", "v2", "v3"]);
495        let ct = res.headers().get(CONTENT_TYPE).unwrap();
496        assert_eq!(ct, HeaderValue::from_static("text/json"));
497        assert_body_eq!(res, br#"["v1","v2","v3"]"#);
498    }
499
500    #[tokio::test(flavor = "local")]
501    async fn test_serde_json_in_body() {
502        let resp = HttpResponse::Ok()
503            .body(serde_json::to_vec(&serde_json::json!({ "test-key": "test-value" })).unwrap());
504
505        assert_eq!(
506            body::to_bytes(resp.into_body()).await.unwrap().as_ref(),
507            br#"{"test-key":"test-value"}"#
508        );
509    }
510
511    #[test]
512    fn response_builder_header_insert_kv() {
513        let mut res = HttpResponse::Ok();
514        res.insert_header(("Content-Type", "application/octet-stream"));
515        let res = res.finish();
516
517        assert_eq!(
518            res.headers().get("Content-Type"),
519            Some(&HeaderValue::from_static("application/octet-stream"))
520        );
521    }
522
523    #[test]
524    fn response_builder_header_insert_typed() {
525        let mut res = HttpResponse::Ok();
526        res.insert_header((header::CONTENT_TYPE, mime::APPLICATION_OCTET_STREAM));
527        let res = res.finish();
528
529        assert_eq!(
530            res.headers().get("Content-Type"),
531            Some(&HeaderValue::from_static("application/octet-stream"))
532        );
533    }
534
535    #[test]
536    fn response_builder_header_append_kv() {
537        let mut res = HttpResponse::Ok();
538        res.append_header(("Content-Type", "application/octet-stream"));
539        res.append_header(("Content-Type", "application/json"));
540        let res = res.finish();
541
542        let headers: Vec<_> = res.headers().get_all("Content-Type").cloned().collect();
543        assert_eq!(headers.len(), 2);
544        assert!(headers.contains(&HeaderValue::from_static("application/octet-stream")));
545        assert!(headers.contains(&HeaderValue::from_static("application/json")));
546    }
547
548    #[test]
549    fn response_builder_header_append_typed() {
550        let mut res = HttpResponse::Ok();
551        res.append_header((header::CONTENT_TYPE, mime::APPLICATION_OCTET_STREAM));
552        res.append_header((header::CONTENT_TYPE, mime::APPLICATION_JSON));
553        let res = res.finish();
554
555        let headers: Vec<_> = res.headers().get_all("Content-Type").cloned().collect();
556        assert_eq!(headers.len(), 2);
557        assert!(headers.contains(&HeaderValue::from_static("application/octet-stream")));
558        assert!(headers.contains(&HeaderValue::from_static("application/json")));
559    }
560}