1use 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
16pub struct Response<B = Body> {
18 body: ResponseBody<B>,
19 head: Message<ResponseHead>,
20}
21
22impl Response<Body> {
23 #[inline]
25 pub fn builder(status: StatusCode) -> ResponseBuilder {
26 ResponseBuilder::new(status)
27 }
28
29 #[inline]
34 pub fn builder_from<T: Into<ResponseBuilder>>(source: T) -> ResponseBuilder {
35 source.into()
36 }
37
38 #[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 #[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 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 #[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 pub fn head(&self) -> &ResponseHead {
85 &self.head
86 }
87
88 #[inline]
89 pub fn head_mut(&mut self) -> &mut ResponseHead {
91 &mut self.head
92 }
93
94 #[inline]
96 pub fn status(&self) -> StatusCode {
97 self.head.status
98 }
99
100 #[inline]
102 pub fn status_mut(&mut self) -> &mut StatusCode {
103 &mut self.head.status
104 }
105
106 #[inline]
108 pub fn headers(&self) -> &HeaderMap {
109 &self.head.headers
110 }
111
112 #[inline]
114 pub fn headers_mut(&mut self) -> &mut HeaderMap {
115 &mut self.head.headers
116 }
117
118 #[cfg(feature = "cookie")]
119 #[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 #[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 #[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 #[inline]
172 pub fn upgrade(&self) -> bool {
173 self.head.upgrade()
174 }
175
176 pub fn keep_alive(&self) -> bool {
178 self.head.keep_alive()
179 }
180
181 #[inline]
183 pub fn extensions(&self) -> Ref<'_, Extensions> {
184 self.head.extensions.borrow()
185 }
186
187 #[inline]
189 pub fn extensions_mut(&self) -> RefMut<'_, Extensions> {
190 self.head.extensions.borrow_mut()
191 }
192
193 #[inline]
195 pub fn body(&self) -> &ResponseBody<B> {
196 &self.body
197 }
198
199 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 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 pub fn drop_body(self) -> Response<()> {
220 Response {
221 head: self.head,
222 body: ResponseBody::Body(()),
223 }
224 }
225
226 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 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 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)]
302pub 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
324pub 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 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 #[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 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 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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 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 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 #[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 #[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 pub fn body<B: Into<Body>>(&mut self, body: B) -> Response {
618 self.message_body(body.into())
619 }
620
621 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 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 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 #[doc(alias = "finish")]
700 pub fn build(&mut self) -> Response {
701 self.body(Body::Empty)
702 }
703
704 #[must_use]
705 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
730impl<B> From<Response<B>> for ResponseBuilder {
732 fn from(res: Response<B>) -> ResponseBuilder {
733 ResponseBuilder {
735 head: Some(res.head),
736 err: None,
737 #[cfg(feature = "cookie")]
738 cookies: Vec::new(),
739 }
740 }
741}
742
743impl<'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 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
794impl<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 #[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 *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 #[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 #[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 #[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 #[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 #[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 #[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 #[test]
1076 fn test_force_close() {
1077 let resp = Response::builder(StatusCode::OK).force_close().build();
1078 assert!(!resp.keep_alive());
1079 }
1080
1081 #[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 #[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 #[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 #[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 #[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 #[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 #[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 let resp = Response::Ok().header("bad name", "value").json(&vec![1, 2]);
1267 assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
1268 }
1269
1270 #[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 #[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 #[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}