Skip to main content

ntex/http/
response.rs

1//! Http response
2use std::{cell::Ref, cell::RefMut, error::Error, fmt, fmt::Write, str};
3
4use serde::Serialize;
5
6#[cfg(feature = "cookie")]
7use coo_kie::Cookie;
8
9use crate::http::StatusCode;
10use crate::http::body::{Body, BodyStream, MessageBody, ResponseBody};
11use crate::http::error::{HttpError, ResponseError};
12use crate::http::header::{self, HeaderMap, HeaderName, HeaderValue};
13use crate::http::message::{ConnectionType, Message, ResponseHead};
14use crate::util::{Bytes, BytesMut, Extensions, Stream};
15
16/// An HTTP response.
17pub struct Response<B = Body> {
18    body: ResponseBody<B>,
19    head: Message<ResponseHead>,
20}
21
22impl Response<Body> {
23    /// Creates a response builder with the given status.
24    #[inline]
25    pub fn builder(status: StatusCode) -> ResponseBuilder {
26        ResponseBuilder::new(status)
27    }
28
29    /// Creates a response builder from another compatible value.
30    ///
31    /// See the `From` implementations of [`ResponseBuilder`] for what is kept;
32    /// building from a [`ResponseHead`] moves its extensions into the builder.
33    #[inline]
34    pub fn builder_from<T: Into<ResponseBuilder>>(source: T) -> ResponseBuilder {
35        source.into()
36    }
37
38    /// Constructs a response.
39    #[inline]
40    pub fn new(status: StatusCode) -> Response {
41        Response {
42            head: Message::with_status(status),
43            body: ResponseBody::Body(Body::Empty),
44        }
45    }
46
47    /// Renders a displayable value as a plain-text response body.
48    #[inline]
49    pub fn render_with<B: fmt::Display>(status: StatusCode, body: &B) -> Response {
50        let mut resp = Response::new(status);
51        let mut buf = BytesMut::new();
52        let _ = write!(&mut buf, "{body}");
53        resp.headers_mut().insert(
54            header::CONTENT_TYPE,
55            header::HeaderValue::from_static("text/plain; charset=utf-8"),
56        );
57        resp.set_body(Body::from(buf))
58    }
59
60    /// Converts the default body into a custom response body type.
61    pub fn into_body<B>(self) -> Response<B> {
62        let b = match self.body {
63            ResponseBody::Body(b) | ResponseBody::Other(b) => b,
64        };
65        Response {
66            head: self.head,
67            body: ResponseBody::Other(b),
68        }
69    }
70}
71
72impl<B> Response<B> {
73    /// Creates a response with the given status and body.
74    #[inline]
75    pub fn with_body(status: StatusCode, body: B) -> Response<B> {
76        Response {
77            head: Message::with_status(status),
78            body: ResponseBody::Body(body),
79        }
80    }
81
82    #[inline]
83    /// Returns the response head.
84    pub fn head(&self) -> &ResponseHead {
85        &self.head
86    }
87
88    #[inline]
89    /// Returns mutable access to the response head.
90    pub fn head_mut(&mut self) -> &mut ResponseHead {
91        &mut self.head
92    }
93
94    /// Returns the response status code.
95    #[inline]
96    pub fn status(&self) -> StatusCode {
97        self.head.status
98    }
99
100    /// Returns mutable access to the response status code.
101    #[inline]
102    pub fn status_mut(&mut self) -> &mut StatusCode {
103        &mut self.head.status
104    }
105
106    /// Returns the response headers.
107    #[inline]
108    pub fn headers(&self) -> &HeaderMap {
109        &self.head.headers
110    }
111
112    /// Returns mutable access to the response headers.
113    #[inline]
114    pub fn headers_mut(&mut self) -> &mut HeaderMap {
115        &mut self.head.headers
116    }
117
118    #[cfg(feature = "cookie")]
119    /// Get an iterator for the cookies set by this response.
120    #[inline]
121    pub fn cookies(&self) -> CookieIter<'_> {
122        CookieIter {
123            iter: self.head.headers.get_all(header::SET_COOKIE),
124        }
125    }
126
127    #[cfg(feature = "cookie")]
128    /// Add a cookie to this response.
129    #[inline]
130    pub fn add_cookie<'a, C>(&mut self, cookie: C) -> Result<(), HttpError>
131    where
132        C: Into<Cookie<'a>>,
133    {
134        let h = &mut self.head.headers;
135        let c = cookie.into();
136        HeaderValue::try_from(c.to_string())
137            .map(|c| {
138                h.append(header::SET_COOKIE, c);
139            })
140            .map_err(Into::into)
141    }
142
143    #[cfg(feature = "cookie")]
144    /// Remove all cookies with the given name from this response.
145    ///
146    /// Returns the number of cookies removed.
147    #[inline]
148    pub fn del_cookie(&mut self, name: &str) -> usize {
149        let h = &mut self.head.headers;
150        let vals: Vec<HeaderValue> = h
151            .get_all(header::SET_COOKIE)
152            .map(ToOwned::to_owned)
153            .collect();
154        h.remove(header::SET_COOKIE);
155
156        let mut count: usize = 0;
157        for v in vals {
158            if let Ok(s) = v.to_str()
159                && let Ok(c) = Cookie::parse_encoded(s)
160                && c.name() == name
161            {
162                count += 1;
163                continue;
164            }
165            h.append(header::SET_COOKIE, v);
166        }
167        count
168    }
169
170    /// Connection upgrade status.
171    #[inline]
172    pub fn upgrade(&self) -> bool {
173        self.head.upgrade()
174    }
175
176    /// Keep-alive status for this connection.
177    pub fn keep_alive(&self) -> bool {
178        self.head.keep_alive()
179    }
180
181    /// Returns the response extensions.
182    #[inline]
183    pub fn extensions(&self) -> Ref<'_, Extensions> {
184        self.head.extensions.borrow()
185    }
186
187    /// Returns mutable access to the response extensions.
188    #[inline]
189    pub fn extensions_mut(&self) -> RefMut<'_, Extensions> {
190        self.head.extensions.borrow_mut()
191    }
192
193    /// Returns the response body.
194    #[inline]
195    pub fn body(&self) -> &ResponseBody<B> {
196        &self.body
197    }
198
199    /// Replaces the response body with a different body type.
200    pub fn set_body<B2>(self, body: B2) -> Response<B2> {
201        Response {
202            head: self.head,
203            body: ResponseBody::Body(body),
204        }
205    }
206
207    /// Splits the response into its metadata and body.
208    pub fn into_parts(self) -> (Response<()>, ResponseBody<B>) {
209        (
210            Response {
211                head: self.head,
212                body: ResponseBody::Body(()),
213            },
214            self.body,
215        )
216    }
217
218    /// Drops the response body while preserving the response head.
219    pub fn drop_body(self) -> Response<()> {
220        Response {
221            head: self.head,
222            body: ResponseBody::Body(()),
223        }
224    }
225
226    /// Transforms the response body and allows its metadata to be updated.
227    pub fn map_body<F, B2>(mut self, f: F) -> Response<B2>
228    where
229        F: FnOnce(&mut ResponseHead, ResponseBody<B>) -> ResponseBody<B2>,
230    {
231        let body = f(&mut self.head, self.body);
232
233        Response {
234            body,
235            head: self.head,
236        }
237    }
238
239    /// Takes the response body, leaving an empty body behind.
240    pub fn take_body(&mut self) -> ResponseBody<B> {
241        self.body.take_body()
242    }
243}
244
245#[cfg(test)]
246impl Response<Body> {
247    pub(crate) fn get_body_ref(&self) -> &[u8] {
248        let b = match *self.body() {
249            ResponseBody::Body(ref b) | ResponseBody::Other(ref b) => b,
250        };
251        if let Body::Bytes(bin) = b { bin } else { panic!() }
252    }
253}
254
255impl Response<Body> {
256    #[must_use]
257    /// Takes the response body while preserving its metadata.
258    ///
259    /// The returned response contains the original body and a copy of the
260    /// response head without its extensions. This response is left with an
261    /// empty body, both responses can be modified independently.
262    pub fn take(&mut self) -> Response {
263        Response {
264            head: self.head.copy(),
265            body: self.body.take_body(),
266        }
267    }
268}
269
270impl<B: MessageBody> fmt::Display for Response<B> {
271    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
272        writeln!(
273            f,
274            "Response<{:?} {}{}>",
275            self.head.version,
276            self.head.status,
277            self.head.reason.unwrap_or(""),
278        )
279    }
280}
281
282impl<B: MessageBody> fmt::Debug for Response<B> {
283    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
284        let res = writeln!(
285            f,
286            "\nResponse {:?} {}{}",
287            self.head.version,
288            self.head.status,
289            self.head.reason.unwrap_or(""),
290        );
291        let _ = writeln!(f, "  headers:");
292        for (key, val) in &self.head.headers {
293            let _ = writeln!(f, "    {key:?}: {val:?}");
294        }
295        let _ = writeln!(f, "  body: {:?}", self.body.size());
296        res
297    }
298}
299
300#[cfg(feature = "cookie")]
301#[derive(Debug)]
302/// Iterator over valid `Set-Cookie` header values in a response.
303///
304/// Malformed header values are skipped.
305pub struct CookieIter<'a> {
306    iter: header::GetAll<'a>,
307}
308
309#[cfg(feature = "cookie")]
310impl<'a> Iterator for CookieIter<'a> {
311    type Item = Cookie<'a>;
312
313    #[inline]
314    fn next(&mut self) -> Option<Cookie<'a>> {
315        for v in self.iter.by_ref() {
316            if let Ok(c) = Cookie::parse_encoded(v.to_str().ok()?) {
317                return Some(c);
318            }
319        }
320        None
321    }
322}
323
324/// An HTTP response builder
325///
326/// This type can be used to construct an instance of `Response` through a
327/// builder-like pattern.
328///
329/// Header conversion errors are stored by the builder. A later call to
330/// [`ResponseBuilder::body`], [`ResponseBuilder::message_body`],
331/// [`ResponseBuilder::streaming`], [`ResponseBuilder::json`], or
332/// [`ResponseBuilder::build`] converts the stored error into an error response.
333/// After an error is stored, subsequent configuration does not affect the
334/// returned response.
335pub struct ResponseBuilder {
336    head: Option<Message<ResponseHead>>,
337    err: Option<HttpError>,
338    #[cfg(feature = "cookie")]
339    cookies: Vec<Cookie<'static>>,
340}
341
342impl ResponseBuilder {
343    #[inline]
344    #[must_use]
345    /// Creates a response builder with the supplied status.
346    pub fn new(status: StatusCode) -> Self {
347        ResponseBuilder {
348            head: Some(Message::with_status(status)),
349            err: None,
350            #[cfg(feature = "cookie")]
351            cookies: Vec::new(),
352        }
353    }
354
355    /// Sets the response status code.
356    #[inline]
357    pub fn status(&mut self, status: StatusCode) -> &mut Self {
358        if let Some(parts) = parts(&mut self.head, self.err) {
359            parts.status = status;
360        }
361        self
362    }
363
364    /// Append a header to existing headers.
365    ///
366    /// ```rust
367    /// use ntex::http::{header, Request, Response};
368    ///
369    /// fn index(req: Request) -> Response {
370    ///     Response::Ok()
371    ///         .header("X-TEST", "value")
372    ///         .header(header::CONTENT_TYPE, "application/json")
373    ///         .build()
374    /// }
375    /// ```
376    pub fn header<K, V>(&mut self, key: K, value: V) -> &mut Self
377    where
378        HeaderName: TryFrom<K>,
379        HeaderValue: TryFrom<V>,
380        <HeaderName as TryFrom<K>>::Error: Into<HttpError>,
381        <HeaderValue as TryFrom<V>>::Error: Into<HttpError>,
382    {
383        if let Some(parts) = parts(&mut self.head, self.err) {
384            match HeaderName::try_from(key) {
385                Ok(key) => match HeaderValue::try_from(value) {
386                    Ok(value) => {
387                        parts.headers.append(key, value);
388                    }
389                    Err(e) => self.err = Some(log_error(e)),
390                },
391                Err(e) => self.err = Some(log_error(e)),
392            }
393        }
394        self
395    }
396
397    /// Sets a header, replacing any existing values with the same name.
398    ///
399    /// ```rust
400    /// use ntex::http::{header, Request, Response};
401    ///
402    /// fn index(req: Request) -> Response {
403    ///     Response::Ok()
404    ///         .set_header("X-TEST", "value")
405    ///         .set_header(header::CONTENT_TYPE, "application/json")
406    ///         .build()
407    /// }
408    /// ```
409    pub fn set_header<K, V>(&mut self, key: K, value: V) -> &mut Self
410    where
411        HeaderName: TryFrom<K>,
412        HeaderValue: TryFrom<V>,
413        <HeaderName as TryFrom<K>>::Error: Into<HttpError>,
414        <HeaderValue as TryFrom<V>>::Error: Into<HttpError>,
415    {
416        if let Some(parts) = parts(&mut self.head, self.err) {
417            match HeaderName::try_from(key) {
418                Ok(key) => match HeaderValue::try_from(value) {
419                    Ok(value) => {
420                        parts.headers.insert(key, value);
421                    }
422                    Err(e) => self.err = Some(log_error(e)),
423                },
424                Err(e) => self.err = Some(log_error(e)),
425            }
426        }
427        self
428    }
429
430    /// Sets a custom HTTP/1 reason phrase.
431    #[inline]
432    pub fn reason(&mut self, reason: &'static str) -> &mut Self {
433        if let Some(parts) = parts(&mut self.head, self.err) {
434            parts.reason = Some(reason);
435        }
436        self
437    }
438
439    /// Marks the response connection as persistent.
440    ///
441    /// Has no effect if the response connection is already marked to be
442    /// closed, see [`ResponseHead::set_connection_type()`].
443    #[inline]
444    pub fn keep_alive(&mut self) -> &mut Self {
445        if let Some(parts) = parts(&mut self.head, self.err) {
446            parts.set_connection_type(ConnectionType::KeepAlive);
447        }
448        self
449    }
450
451    /// Marks the connection as upgraded and sets the `Upgrade` header.
452    #[inline]
453    pub fn upgrade<V>(&mut self, value: V) -> &mut Self
454    where
455        HeaderValue: TryFrom<V>,
456        <HeaderValue as TryFrom<V>>::Error: Into<HttpError>,
457    {
458        if let Some(parts) = parts(&mut self.head, self.err) {
459            parts.set_connection_type(ConnectionType::Upgrade);
460        }
461        self.set_header(header::UPGRADE, value)
462    }
463
464    /// Forces the connection to close after this response.
465    #[inline]
466    pub fn force_close(&mut self) -> &mut Self {
467        if let Some(parts) = parts(&mut self.head, self.err) {
468            parts.set_connection_type(ConnectionType::Close);
469        }
470        self
471    }
472
473    /// Disable chunked transfer encoding for HTTP/1.1 streaming responses.
474    #[inline]
475    pub fn no_chunking(&mut self) -> &mut Self {
476        if let Some(parts) = parts(&mut self.head, self.err) {
477            parts.no_chunking(true);
478        }
479        self
480    }
481
482    /// Sets the `Content-Type` header.
483    #[inline]
484    pub fn content_type<V>(&mut self, value: V) -> &mut Self
485    where
486        HeaderValue: TryFrom<V>,
487        <HeaderValue as TryFrom<V>>::Error: Into<HttpError>,
488    {
489        if let Some(parts) = parts(&mut self.head, self.err) {
490            match HeaderValue::try_from(value) {
491                Ok(value) => {
492                    parts.headers.insert(header::CONTENT_TYPE, value);
493                }
494                Err(e) => self.err = Some(log_error(e)),
495            }
496        }
497        self
498    }
499
500    /// Appends a `Content-Length` header.
501    #[inline]
502    pub fn content_length(&mut self, len: u64) -> &mut Self {
503        self.header(header::CONTENT_LENGTH, len)
504    }
505
506    #[cfg(feature = "cookie")]
507    /// Set a cookie.
508    ///
509    /// A cookie is identified by its name, path, and domain. Setting a cookie
510    /// replaces a cookie previously set or deleted by this builder with the
511    /// same name, path, and domain; cookies with the same name but a different
512    /// path or domain are kept.
513    ///
514    /// ```rust
515    /// use coo_kie as cookie;
516    /// use ntex::http::{Request, Response};
517    ///
518    /// fn index(req: Request) -> Response {
519    ///     Response::Ok()
520    ///         .cookie(
521    ///             cookie::Cookie::build(("name", "value"))
522    ///                 .domain("www.rust-lang.org")
523    ///                 .path("/")
524    ///                 .secure(true)
525    ///                 .http_only(true)
526    ///         )
527    ///         .build()
528    /// }
529    /// ```
530    pub fn cookie<C>(&mut self, cookie: C) -> &mut Self
531    where
532        C: Into<Cookie<'static>>,
533    {
534        self.set_cookie(cookie.into());
535        self
536    }
537
538    #[cfg(feature = "cookie")]
539    /// Remove cookie.
540    ///
541    /// Adds a removal cookie, an empty cookie that has already expired, with
542    /// the name, path, and domain of `cookie`. It replaces a cookie previously
543    /// set or deleted by this builder with the same name, path, and domain.
544    ///
545    /// A client removes a stored cookie only if the path and domain match the
546    /// ones it was set with. Request cookies carry only a name and a value, so
547    /// the path and domain of a cookie set with them must be added before
548    /// deletion.
549    ///
550    /// ```rust
551    /// use ntex::http::{Request, Response, HttpMessage};
552    ///
553    /// fn index(req: Request) -> Response {
554    ///     let mut builder = Response::Ok();
555    ///
556    ///     if let Some(mut cookie) = req.cookie("name") {
557    ///         // the cookie was set with `Path=/app`
558    ///         cookie.set_path("/app");
559    ///         builder.del_cookie(&cookie);
560    ///     }
561    ///
562    ///     builder.build()
563    /// }
564    /// ```
565    pub fn del_cookie(&mut self, cookie: &Cookie<'_>) -> &mut Self {
566        let mut cookie = cookie.clone().into_owned();
567        cookie.make_removal();
568        self.set_cookie(cookie);
569        self
570    }
571
572    #[cfg(feature = "cookie")]
573    fn set_cookie(&mut self, cookie: Cookie<'static>) {
574        let same_scope = |c: &Cookie<'_>| {
575            c.name() == cookie.name()
576                && c.path() == cookie.path()
577                && match (c.domain(), cookie.domain()) {
578                    (Some(d1), Some(d2)) => d1.eq_ignore_ascii_case(d2),
579                    (d1, d2) => d1 == d2,
580                }
581        };
582        if let Some(c) = self.cookies.iter_mut().find(|c| same_scope(c)) {
583            *c = cookie;
584        } else {
585            self.cookies.push(cookie);
586        }
587    }
588
589    /// Returns the response extensions.
590    ///
591    /// # Panics
592    ///
593    /// Panics if the builder has already produced or transferred a response.
594    #[inline]
595    pub fn extensions(&self) -> Ref<'_, Extensions> {
596        let head = self.head.as_ref().expect("cannot reuse response builder");
597        head.extensions.borrow()
598    }
599
600    /// Returns mutable access to the response extensions.
601    ///
602    /// # Panics
603    ///
604    /// Panics if the builder has already produced or transferred a response.
605    #[inline]
606    pub fn extensions_mut(&self) -> RefMut<'_, Extensions> {
607        let head = self.head.as_ref().expect("cannot reuse response builder");
608        head.extensions.borrow_mut()
609    }
610
611    #[inline]
612    /// Sets a body and creates the response.
613    ///
614    /// # Panics
615    ///
616    /// Panics if the builder has already produced or transferred a response.
617    pub fn body<B: Into<Body>>(&mut self, body: B) -> Response {
618        self.message_body(body.into())
619    }
620
621    /// Sets a typed body and creates the response.
622    ///
623    /// # Panics
624    ///
625    /// Panics if the builder has already produced or transferred a response.
626    pub fn message_body<B>(&mut self, body: B) -> Response<B> {
627        if let Some(e) = self.err.take() {
628            return Response::from(e).into_body();
629        }
630
631        #[allow(unused_mut)]
632        let mut response = self.head.take().expect("cannot reuse response builder");
633
634        #[cfg(feature = "cookie")]
635        for cookie in &self.cookies {
636            match HeaderValue::from_str(&cookie.to_string()) {
637                Ok(val) => response.headers.append(header::SET_COOKIE, val),
638                Err(e) => return Response::from(HttpError::from(e)).into_body(),
639            }
640        }
641
642        Response {
643            head: response,
644            body: ResponseBody::Body(body),
645        }
646    }
647
648    #[inline]
649    #[must_use]
650    /// Sets a streaming body and creates the response.
651    ///
652    /// # Panics
653    ///
654    /// Panics if the builder has already produced or transferred a response.
655    pub fn streaming<S, E>(&mut self, stream: S) -> Response
656    where
657        S: Stream<Item = Result<Bytes, E>> + Unpin + 'static,
658        E: Error + 'static,
659    {
660        self.body(Body::from_message(BodyStream::new(stream)))
661    }
662
663    #[must_use]
664    /// Serializes `value` as JSON and creates the response.
665    ///
666    /// Sets `Content-Type: application/json` unless a content type is already
667    /// present. If serialization fails, the serialization error is converted
668    /// into an HTTP error response.
669    ///
670    /// # Panics
671    ///
672    /// Panics if serialization succeeds after the builder has already
673    /// produced or transferred a response.
674    pub fn json<T: Serialize>(&mut self, value: &T) -> Response {
675        match super::json::to_bytes(value) {
676            Ok(body) => {
677                let contains = if let Some(parts) = parts(&mut self.head, self.err) {
678                    parts.headers.contains_key(header::CONTENT_TYPE)
679                } else {
680                    true
681                };
682                if !contains {
683                    self.header(header::CONTENT_TYPE, "application/json");
684                }
685
686                self.body(Body::from(body))
687            }
688            Err(e) => e.into(),
689        }
690    }
691
692    #[inline]
693    #[must_use]
694    /// Creates the response with an empty body.
695    ///
696    /// # Panics
697    ///
698    /// Panics if the builder has already produced or transferred a response.
699    #[doc(alias = "finish")]
700    pub fn build(&mut self) -> Response {
701        self.body(Body::Empty)
702    }
703
704    #[must_use]
705    /// Transfers the builder state into a new builder.
706    ///
707    /// The current builder is left consumed and cannot produce a response.
708    pub fn take(&mut self) -> ResponseBuilder {
709        ResponseBuilder {
710            head: self.head.take(),
711            err: self.err.take(),
712            #[cfg(feature = "cookie")]
713            cookies: std::mem::take(&mut self.cookies),
714        }
715    }
716}
717
718#[inline]
719#[allow(clippy::ref_option)]
720fn parts(
721    parts: &mut Option<Message<ResponseHead>>,
722    err: Option<HttpError>,
723) -> Option<&mut ResponseHead> {
724    if err.is_some() {
725        return None;
726    }
727    parts.as_mut().map(|r| &mut **r)
728}
729
730/// Convert `Response` to a `ResponseBuilder`. Body get dropped.
731impl<B> From<Response<B>> for ResponseBuilder {
732    fn from(res: Response<B>) -> ResponseBuilder {
733        // existing `Set-Cookie` headers are kept in the head
734        ResponseBuilder {
735            head: Some(res.head),
736            err: None,
737            #[cfg(feature = "cookie")]
738            cookies: Vec::new(),
739        }
740    }
741}
742
743/// Convert `ResponseHead` to a `ResponseBuilder`.
744///
745/// Status, version, reason, headers, connection type, and chunking policy are
746/// copied. Extensions cannot be cloned, so they are moved into the builder and
747/// `head` is left with empty extensions.
748impl<'a> From<&'a ResponseHead> for ResponseBuilder {
749    fn from(head: &'a ResponseHead) -> ResponseBuilder {
750        let mut msg = Message::with_status(head.status);
751        msg.version = head.version;
752        msg.reason = head.reason;
753        for (k, v) in &head.headers {
754            msg.headers.append(k.clone(), v.clone());
755        }
756        msg.flags = head.flags;
757        *msg.extensions.get_mut() = std::mem::take(&mut *head.extensions.borrow_mut());
758
759        // existing `Set-Cookie` headers are copied into the head
760        ResponseBuilder {
761            head: Some(msg),
762            err: None,
763            #[cfg(feature = "cookie")]
764            cookies: Vec::new(),
765        }
766    }
767}
768
769impl fmt::Debug for ResponseBuilder {
770    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
771        let head = self.head.as_ref().unwrap();
772
773        let res = writeln!(
774            f,
775            "\nResponseBuilder {:?} {}{}",
776            head.version,
777            head.status,
778            head.reason.unwrap_or(""),
779        );
780        let _ = writeln!(f, "  headers:");
781        for (key, val) in &head.headers {
782            let _ = writeln!(f, "    {key:?}: {val:?}");
783        }
784        res
785    }
786}
787
788fn log_error<T: Into<HttpError>>(err: T) -> HttpError {
789    let e = err.into();
790    log::error!("Error in ResponseBuilder {e}");
791    e
792}
793
794/// Helper converters
795impl<I: Into<Response>, E> From<Result<I, E>> for Response
796where
797    E: ResponseError + fmt::Debug,
798{
799    fn from(res: Result<I, E>) -> Self {
800        match res {
801            Ok(val) => val.into(),
802            Err(err) => err.into(),
803        }
804    }
805}
806
807impl From<ResponseBuilder> for Response {
808    fn from(mut builder: ResponseBuilder) -> Self {
809        builder.build()
810    }
811}
812
813impl From<&'static str> for Response {
814    fn from(val: &'static str) -> Self {
815        Response::Ok()
816            .content_type("text/plain; charset=utf-8")
817            .body(val)
818    }
819}
820
821impl From<&'static [u8]> for Response {
822    fn from(val: &'static [u8]) -> Self {
823        Response::Ok()
824            .content_type("application/octet-stream")
825            .body(val)
826    }
827}
828
829impl From<String> for Response {
830    fn from(val: String) -> Self {
831        Response::Ok()
832            .content_type("text/plain; charset=utf-8")
833            .body(val)
834    }
835}
836
837impl<'a> From<&'a String> for Response {
838    fn from(val: &'a String) -> Self {
839        Response::Ok()
840            .content_type("text/plain; charset=utf-8")
841            .body(val)
842    }
843}
844
845impl From<Bytes> for Response {
846    fn from(val: Bytes) -> Self {
847        Response::Ok()
848            .content_type("application/octet-stream")
849            .body(val)
850    }
851}
852
853impl From<BytesMut> for Response {
854    fn from(val: BytesMut) -> Self {
855        Response::Ok()
856            .content_type("application/octet-stream")
857            .body(val)
858    }
859}
860
861impl<B: MessageBody> Error for Response<B> {}
862
863#[cfg(test)]
864mod tests {
865    use super::*;
866    use crate::http::header::{CONTENT_TYPE, COOKIE};
867
868    /// STATEMENT: Taking a response transfers its body into an independent head without copying extensions.
869    ///
870    /// HOW:
871    /// - Take a response with custom status, reason, headers, body, and extension, then mutate both results.
872    /// - Check copied metadata, transferred body, independent headers/status, and original-only extensions.
873    #[test]
874    fn test_take_copies_head() {
875        let mut resp = Response::NotFound()
876            .header(CONTENT_TYPE, "text/plain")
877            .reason("Nope")
878            .body("body");
879        resp.extensions_mut().insert(1u8);
880
881        let mut taken = resp.take();
882        assert_eq!(taken.status(), StatusCode::NOT_FOUND);
883        assert_eq!(taken.head().reason, Some("Nope"));
884        assert_eq!(taken.headers().get(CONTENT_TYPE).unwrap(), "text/plain");
885        assert_eq!(taken.get_body_ref(), b"body");
886        assert!(taken.extensions().get::<u8>().is_none());
887
888        // both responses can be modified
889        *taken.status_mut() = StatusCode::OK;
890        taken.headers_mut().remove(CONTENT_TYPE);
891        resp.headers_mut()
892            .insert(COOKIE, HeaderValue::from_static("a=b"));
893        assert_eq!(resp.status(), StatusCode::NOT_FOUND);
894        assert!(resp.headers().contains_key(CONTENT_TYPE));
895        assert!(!taken.headers().contains_key(COOKIE));
896        assert_eq!(resp.extensions().get::<u8>(), Some(&1));
897    }
898
899    /// STATEMENT: Response, head, and builder debug output identify their respective types.
900    ///
901    /// HOW:
902    /// - Format responses and a builder with repeated cookie headers and check the type labels.
903    #[test]
904    fn test_debug() {
905        let resp = Response::Ok()
906            .header(COOKIE, HeaderValue::from_static("cookie1=value1; "))
907            .header(COOKIE, HeaderValue::from_static("cookie2=value2; "))
908            .build();
909        let dbg = format!("{resp:?}");
910        assert!(dbg.contains("Response"));
911        let dbg = format!("{:?}", resp.head());
912        assert!(dbg.contains("ResponseHead"));
913
914        let mut resp = Response::Ok();
915        resp.header(COOKIE, HeaderValue::from_static("cookie1=value1; "));
916        resp.header(COOKIE, HeaderValue::from_static("cookie2=value2; "));
917        let dbg = format!("{resp:?}");
918        assert!(dbg.contains("ResponseBuilder"));
919    }
920
921    /// STATEMENT: Response cookie builders preserve attributes and encode deletion as an expired empty cookie.
922    ///
923    /// HOW:
924    /// - Parse request cookies, delete one, add a fully attributed response cookie, and compare emitted headers.
925    #[cfg(feature = "cookie")]
926    #[test]
927    fn test_response_cookies() {
928        use crate::http::header::{COOKIE, SET_COOKIE};
929        use crate::http::httpmessage::HttpMessage;
930
931        let req = crate::http::test::TestRequest::default()
932            .header(COOKIE, "cookie1=value1")
933            .header(COOKIE, "cookie2=value2")
934            .build();
935        let cookies = req.cookies().unwrap();
936
937        let resp = Response::Ok()
938            .cookie(
939                coo_kie::Cookie::build(("name", "value"))
940                    .domain("www.rust-lang.org")
941                    .path("/test")
942                    .http_only(true)
943                    .max_age(time::Duration::days(1)),
944            )
945            .del_cookie(&cookies[0])
946            .build();
947
948        let mut val: Vec<_> = resp
949            .headers()
950            .get_all(SET_COOKIE)
951            .map(|v| v.to_str().unwrap().to_owned())
952            .collect();
953        val.sort();
954        assert!(val[0].starts_with("cookie1=; Max-Age=0;"));
955        assert_eq!(
956            val[1],
957            "name=value; HttpOnly; Path=/test; Domain=www.rust-lang.org; Max-Age=86400"
958        );
959    }
960
961    /// STATEMENT: Builder cookies are identified by name, path, and domain, so cookies that
962    /// share a name but differ in scope are all emitted and a same-scope cookie is replaced.
963    ///
964    /// HOW:
965    /// - Set `sid` for paths `/` and `/admin`, `sid` for domain `a.example`, then `sid` for
966    ///   `/` again, `sid` for `A.EXAMPLE`, and `sid` without path or domain.
967    /// - Confirm the `Set-Cookie` headers hold, in insertion order, the replaced `/` cookie,
968    ///   the `/admin` cookie, the replaced domain cookie, and the unscoped cookie.
969    /// - Delete `sid` for `/admin` and confirm only that cookie becomes an expired empty
970    ///   cookie which keeps `Path=/admin`.
971    #[cfg(feature = "cookie")]
972    #[test]
973    fn test_builder_cookie_scope() {
974        let resp = Response::Ok()
975            .cookie(Cookie::build(("sid", "1")).path("/"))
976            .cookie(Cookie::build(("sid", "2")).path("/admin"))
977            .cookie(Cookie::build(("sid", "3")).domain("a.example"))
978            .cookie(Cookie::build(("sid", "4")).path("/"))
979            .cookie(Cookie::build(("sid", "5")).domain("A.EXAMPLE"))
980            .cookie(Cookie::new("sid", "6"))
981            .build();
982        assert_eq!(
983            set_cookies(&resp),
984            [
985                "sid=4; Path=/",
986                "sid=2; Path=/admin",
987                "sid=5; Domain=A.EXAMPLE",
988                "sid=6"
989            ]
990        );
991
992        let resp = Response::Ok()
993            .cookie(Cookie::build(("sid", "1")).path("/"))
994            .cookie(Cookie::build(("sid", "2")).path("/admin"))
995            .del_cookie(&Cookie::build("sid").path("/admin").build())
996            .build();
997        let vals = set_cookies(&resp);
998        assert_eq!(vals.len(), 2);
999        assert_eq!(vals[0], "sid=1; Path=/");
1000        assert!(
1001            vals[1].starts_with("sid=; Path=/admin; Max-Age=0; Expires="),
1002            "{}",
1003            vals[1]
1004        );
1005    }
1006
1007    #[cfg(feature = "cookie")]
1008    fn set_cookies<B>(resp: &Response<B>) -> Vec<String> {
1009        resp.headers()
1010            .get_all(header::SET_COOKIE)
1011            .map(|v| v.to_str().unwrap().to_owned())
1012            .collect()
1013    }
1014
1015    /// STATEMENT: Deleting a response cookie removes every matching name while retaining unrelated cookies.
1016    ///
1017    /// HOW:
1018    /// - Append repeated cookie names, verify their count, delete the repeated name, and inspect remaining cookies.
1019    #[cfg(feature = "cookie")]
1020    #[test]
1021    fn test_update_response_cookies() {
1022        let mut r = Response::Ok()
1023            .cookie(coo_kie::Cookie::new("original", "val100"))
1024            .build();
1025
1026        r.add_cookie(coo_kie::Cookie::new("cookie2", "val200"))
1027            .unwrap();
1028        r.add_cookie(coo_kie::Cookie::new("cookie2", "val250"))
1029            .unwrap();
1030        r.add_cookie(coo_kie::Cookie::new("cookie3", "val300"))
1031            .unwrap();
1032
1033        assert_eq!(r.cookies().count(), 4);
1034        r.del_cookie("cookie2");
1035
1036        let mut iter = r.cookies();
1037        let v = iter.next().unwrap();
1038        assert_eq!((v.name(), v.value()), ("original", "val100"));
1039        let v = iter.next().unwrap();
1040        assert_eq!((v.name(), v.value()), ("cookie3", "val300"));
1041    }
1042
1043    /// STATEMENT: A response builder keeps the selected status and the custom header it was given.
1044    ///
1045    /// HOW:
1046    /// - Build an OK response with an `X-TEST` header.
1047    /// - Check the status is `OK` and the header value is `value`.
1048    #[test]
1049    fn test_basic_builder() {
1050        let resp = Response::Ok().header("X-TEST", "value").build();
1051        assert_eq!(resp.status(), StatusCode::OK);
1052        assert_eq!(resp.headers().get("X-TEST").unwrap(), "value");
1053    }
1054
1055    /// STATEMENT: Response upgrade configuration records both upgrade state and protocol header.
1056    ///
1057    /// HOW:
1058    /// - Build a WebSocket upgrade response and verify its upgrade predicate and header value.
1059    #[test]
1060    fn test_upgrade() {
1061        let resp = Response::builder(StatusCode::OK)
1062            .upgrade("websocket")
1063            .build();
1064        assert!(resp.upgrade());
1065        assert_eq!(
1066            resp.headers().get(header::UPGRADE).unwrap(),
1067            HeaderValue::from_static("websocket")
1068        );
1069    }
1070
1071    /// STATEMENT: A force-close response does not advertise keepalive.
1072    ///
1073    /// HOW:
1074    /// - Apply force-close to a response builder and verify its persistence predicate is false.
1075    #[test]
1076    fn test_force_close() {
1077        let resp = Response::builder(StatusCode::OK).force_close().build();
1078        assert!(!resp.keep_alive());
1079    }
1080
1081    /// STATEMENT: Response content-type configuration survives body construction.
1082    ///
1083    /// HOW:
1084    /// - Set a plain-text media type, build an empty body, and inspect the resulting header.
1085    #[test]
1086    fn test_content_type() {
1087        let resp = Response::builder(StatusCode::OK)
1088            .content_type("text/plain")
1089            .body(Body::Empty);
1090        assert_eq!(resp.headers().get(CONTENT_TYPE).unwrap(), "text/plain");
1091    }
1092
1093    /// STATEMENT: JSON responses serialize their body and supply the default JSON media type.
1094    ///
1095    /// HOW:
1096    /// - Build a response from a string vector and compare its content type and serialized bytes.
1097    #[test]
1098    fn test_json() {
1099        let resp = Response::builder(StatusCode::OK).json(&vec!["v1", "v2", "v3"]);
1100        let ct = resp.headers().get(CONTENT_TYPE).unwrap();
1101        assert_eq!(ct, HeaderValue::from_static("application/json"));
1102        assert_eq!(resp.get_body_ref(), b"[\"v1\",\"v2\",\"v3\"]");
1103    }
1104
1105    /// STATEMENT: JSON response construction preserves an explicitly supplied content type.
1106    ///
1107    /// HOW:
1108    /// - Set a nondefault JSON media type, serialize a vector, and compare header and body.
1109    #[test]
1110    fn test_json_ct() {
1111        let resp = Response::builder(StatusCode::OK)
1112            .header(CONTENT_TYPE, "text/json")
1113            .json(&vec!["v1", "v2", "v3"]);
1114        let ct = resp.headers().get(CONTENT_TYPE).unwrap();
1115        assert_eq!(ct, HeaderValue::from_static("text/json"));
1116        assert_eq!(resp.get_body_ref(), b"[\"v1\",\"v2\",\"v3\"]");
1117    }
1118
1119    /// STATEMENT: String and byte conversions select appropriate response media types and preserve body data.
1120    ///
1121    /// HOW:
1122    /// - Convert borrowed/owned strings and byte buffers, checking OK status, media type, and bytes.
1123    /// - Convert a taken keepalive builder into a response and verify its status.
1124    #[test]
1125    fn test_into_response() {
1126        let resp: Response = "test".into();
1127        assert_eq!(resp.status(), StatusCode::OK);
1128        assert_eq!(
1129            resp.headers().get(CONTENT_TYPE).unwrap(),
1130            HeaderValue::from_static("text/plain; charset=utf-8")
1131        );
1132        assert_eq!(resp.status(), StatusCode::OK);
1133        assert_eq!(resp.get_body_ref(), b"test");
1134
1135        let resp: Response = b"test".as_ref().into();
1136        assert_eq!(resp.status(), StatusCode::OK);
1137        assert_eq!(
1138            resp.headers().get(CONTENT_TYPE).unwrap(),
1139            HeaderValue::from_static("application/octet-stream")
1140        );
1141        assert_eq!(resp.status(), StatusCode::OK);
1142        assert_eq!(resp.get_body_ref(), b"test");
1143
1144        let resp: Response = "test".to_owned().into();
1145        assert_eq!(resp.status(), StatusCode::OK);
1146        assert_eq!(
1147            resp.headers().get(CONTENT_TYPE).unwrap(),
1148            HeaderValue::from_static("text/plain; charset=utf-8")
1149        );
1150        assert_eq!(resp.status(), StatusCode::OK);
1151        assert_eq!(resp.get_body_ref(), b"test");
1152
1153        let resp: Response = (&"test".to_owned()).into();
1154        assert_eq!(resp.status(), StatusCode::OK);
1155        assert_eq!(
1156            resp.headers().get(CONTENT_TYPE).unwrap(),
1157            HeaderValue::from_static("text/plain; charset=utf-8")
1158        );
1159        assert_eq!(resp.status(), StatusCode::OK);
1160        assert_eq!(resp.get_body_ref(), b"test");
1161
1162        let b = Bytes::from_static(b"test");
1163        let resp: Response = b.into();
1164        assert_eq!(resp.status(), StatusCode::OK);
1165        assert_eq!(
1166            resp.headers().get(CONTENT_TYPE).unwrap(),
1167            HeaderValue::from_static("application/octet-stream")
1168        );
1169        assert_eq!(resp.status(), StatusCode::OK);
1170        assert_eq!(resp.get_body_ref(), b"test");
1171
1172        let b = Bytes::from_static(b"test");
1173        let resp: Response = b.into();
1174        assert_eq!(resp.status(), StatusCode::OK);
1175        assert_eq!(
1176            resp.headers().get(CONTENT_TYPE).unwrap(),
1177            HeaderValue::from_static("application/octet-stream")
1178        );
1179        assert_eq!(resp.status(), StatusCode::OK);
1180        assert_eq!(resp.get_body_ref(), b"test");
1181
1182        let b = BytesMut::from("test");
1183        let resp: Response = b.into();
1184        assert_eq!(resp.status(), StatusCode::OK);
1185        assert_eq!(
1186            resp.headers().get(CONTENT_TYPE).unwrap(),
1187            HeaderValue::from_static("application/octet-stream")
1188        );
1189
1190        assert_eq!(resp.status(), StatusCode::OK);
1191        assert_eq!(resp.get_body_ref(), b"test");
1192
1193        let builder = Response::builder_from(ResponseBuilder::new(StatusCode::OK))
1194            .keep_alive()
1195            .take();
1196        let _ = builder.extensions();
1197        let resp: Response = builder.into();
1198        assert_eq!(resp.status(), StatusCode::OK);
1199    }
1200
1201    /// STATEMENT: Converting response heads or whole responses into builders preserves cookies while allowing status changes.
1202    ///
1203    /// HOW:
1204    /// - Convert a response through both builder forms, replace its status, and inspect status and optional cookie values.
1205    #[test]
1206    fn test_into_builder() {
1207        #[allow(unused_mut)]
1208        let mut resp: Response = "test".into();
1209        assert_eq!(resp.status(), StatusCode::OK);
1210
1211        #[cfg(feature = "cookie")]
1212        resp.add_cookie(coo_kie::Cookie::new("cookie1", "val100"))
1213            .unwrap();
1214        let (resp, _) = resp.into_parts();
1215
1216        let mut builder: ResponseBuilder = resp.head().into();
1217        let resp = builder.status(StatusCode::BAD_REQUEST).build();
1218        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
1219
1220        #[cfg(feature = "cookie")]
1221        {
1222            let cookie = resp.cookies().next().unwrap();
1223            assert_eq!((cookie.name(), cookie.value()), ("cookie1", "val100"));
1224        }
1225
1226        let mut builder: ResponseBuilder = resp.into();
1227        let resp = builder.status(StatusCode::BAD_REQUEST).build();
1228        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
1229
1230        #[cfg(feature = "cookie")]
1231        {
1232            let cookie = resp.cookies().next().unwrap();
1233            assert_eq!((cookie.name(), cookie.value()), ("cookie1", "val100"));
1234        }
1235    }
1236
1237    /// STATEMENT: Response display includes version, status, canonical text, and a custom reason.
1238    ///
1239    /// HOW:
1240    /// - Format a not-found response with a custom reason and compare the complete display string.
1241    #[test]
1242    fn test_display() {
1243        let resp = Response::NotFound().reason(" Nope").build();
1244        assert_eq!(resp.to_string(), "Response<HTTP/1.1 404 Not Found Nope>\n");
1245    }
1246
1247    /// STATEMENT: Invalid response header names or values produce server errors, including when JSON is added afterward.
1248    ///
1249    /// HOW:
1250    /// - Exercise append, replace, and content-type setters with malformed input and inspect final statuses.
1251    /// - Add JSON after an invalid header and verify it does not hide the builder error.
1252    #[test]
1253    fn test_builder_invalid_headers() {
1254        let resp = Response::Ok().header("bad name", "value").build();
1255        assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
1256        let resp = Response::Ok().header("x-name", "bad\nvalue").build();
1257        assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
1258        let resp = Response::Ok().set_header("bad name", "value").build();
1259        assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
1260        let resp = Response::Ok().set_header("x-name", "bad\nvalue").build();
1261        assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
1262        let resp = Response::Ok().content_type("bad\nvalue").build();
1263        assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
1264
1265        // json does not replace the error
1266        let resp = Response::Ok().header("bad name", "value").json(&vec![1, 2]);
1267        assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
1268    }
1269
1270    /// STATEMENT: JSON serialization failure becomes an internal-server-error response.
1271    ///
1272    /// HOW:
1273    /// - Serialize a map with unsupported vector keys and inspect the response status.
1274    #[test]
1275    fn test_json_error() {
1276        let mut map = std::collections::HashMap::new();
1277        map.insert(vec![1u8], 1);
1278        let resp = Response::Ok().json(&map);
1279        assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
1280    }
1281
1282    /// STATEMENT: Cookie response handling supports deletion and builder conversion while rejecting invalid values.
1283    ///
1284    /// HOW:
1285    /// - Inspect deletion cookies, build a cookie with a newline, and check its server-error response.
1286    /// - Convert a two-cookie response through head and response builders and verify both cookies remain.
1287    #[cfg(feature = "cookie")]
1288    #[test]
1289    fn test_cookies() {
1290        let cookie = Cookie::new("name", "value");
1291        let resp = Response::Ok().del_cookie(&cookie).build();
1292        let c = resp.cookies().next().unwrap();
1293        assert_eq!(c.name(), "name");
1294        assert_eq!(c.value(), "");
1295
1296        let resp = Response::Ok()
1297            .cookie(Cookie::new("name", "bad\nvalue"))
1298            .build();
1299        assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
1300
1301        let resp = Response::Ok()
1302            .cookie(Cookie::new("c1", "v1"))
1303            .cookie(Cookie::new("c2", "v2"))
1304            .build();
1305        let mut builder = ResponseBuilder::from(resp.head());
1306        let resp2 = builder.build();
1307        assert_eq!(resp2.cookies().count(), 2);
1308        let mut builder = ResponseBuilder::from(resp);
1309        let resp3 = builder.build();
1310        assert_eq!(resp3.cookies().count(), 2);
1311    }
1312
1313    /// STATEMENT: Building from a `ResponseHead` keeps its connection type and moves its
1314    /// extensions out of the source head.
1315    ///
1316    /// HOW:
1317    /// - Build a forced-close, non-chunked response with a `u32` extension.
1318    /// - Create a builder from its head and build a new response.
1319    /// - Confirm the new response has `ConnectionType::Close`, no chunking, and the
1320    ///   extension, and the source head no longer has the extension.
1321    #[test]
1322    fn test_builder_from_head_keeps_state() {
1323        let resp = Response::Ok().force_close().no_chunking().build();
1324        resp.extensions_mut().insert(7u32);
1325        let resp2 = Response::builder_from(resp.head()).build();
1326        assert_eq!(resp2.head().connection_type(), ConnectionType::Close);
1327        assert!(!resp2.head().chunked());
1328        assert_eq!(resp2.extensions().get::<u32>(), Some(&7));
1329        assert!(resp.extensions().get::<u32>().is_none());
1330    }
1331}