1use std::{
2 cell::{Ref, RefMut},
3 fmt,
4};
5
6use actix_http::{
7 body::{BoxBody, EitherBody, MessageBody},
8 header::HeaderMap,
9 Extensions, Response, ResponseHead, StatusCode,
10};
11#[cfg(any(feature = "cookies", feature = "cookies-0_18"))]
12use actix_http::{
13 error::HttpError,
14 header::{self, HeaderValue},
15};
16#[cfg(feature = "cookies")]
17use cookie::Cookie;
18#[cfg(all(feature = "cookies-0_18", not(feature = "cookies")))]
19use cookie_0_18::Cookie;
20
21use crate::{error::Error, HttpRequest, HttpResponseBuilder, Responder};
22
23pub struct HttpResponse<B = BoxBody> {
25 res: Response<B>,
26 error: Option<Error>,
27}
28
29impl HttpResponse<BoxBody> {
30 #[inline]
32 pub fn new(status: StatusCode) -> Self {
33 Self {
34 res: Response::new(status),
35 error: None,
36 }
37 }
38
39 #[inline]
41 pub fn build(status: StatusCode) -> HttpResponseBuilder {
42 HttpResponseBuilder::new(status)
43 }
44
45 #[inline]
47 pub fn from_error(error: impl Into<Error>) -> Self {
48 let error = error.into();
49 let mut response = error.as_response_error().error_response();
50 response.error = Some(error);
51 response
52 }
53}
54
55impl<B> HttpResponse<B> {
56 #[inline]
58 pub fn with_body(status: StatusCode, body: B) -> Self {
59 Self {
60 res: Response::with_body(status, body),
61 error: None,
62 }
63 }
64
65 #[inline]
67 pub fn head(&self) -> &ResponseHead {
68 self.res.head()
69 }
70
71 #[inline]
73 pub fn head_mut(&mut self) -> &mut ResponseHead {
74 self.res.head_mut()
75 }
76
77 #[inline]
79 pub fn error(&self) -> Option<&Error> {
80 self.error.as_ref()
81 }
82
83 #[inline]
85 pub fn status(&self) -> StatusCode {
86 self.res.status()
87 }
88
89 #[inline]
91 pub fn status_mut(&mut self) -> &mut StatusCode {
92 self.res.status_mut()
93 }
94
95 #[inline]
97 pub fn headers(&self) -> &HeaderMap {
98 self.res.headers()
99 }
100
101 #[inline]
103 pub fn headers_mut(&mut self) -> &mut HeaderMap {
104 self.res.headers_mut()
105 }
106
107 #[cfg(feature = "cookies-0_18")]
109 pub fn cookies_0_18(&self) -> impl Iterator<Item = cookie_0_18::Cookie<'_>> {
110 self.headers()
111 .get_all(header::SET_COOKIE)
112 .filter_map(|header| cookie_0_18::Cookie::parse_encoded(header.to_str().ok()?).ok())
113 }
114
115 #[cfg(feature = "cookies-0_18")]
117 pub fn add_cookie_0_18(&mut self, cookie: &cookie_0_18::Cookie<'_>) -> Result<(), HttpError> {
118 let value = HeaderValue::from_str(&cookie.to_string())?;
119 self.headers_mut().append(header::SET_COOKIE, value);
120 Ok(())
121 }
122
123 #[cfg(feature = "cookies-0_18")]
125 pub fn add_removal_cookie_0_18(
126 &mut self,
127 cookie: &cookie_0_18::Cookie<'_>,
128 ) -> Result<(), HttpError> {
129 let mut cookie = cookie.clone();
130 cookie.make_removal();
131 self.add_cookie_0_18(&cookie)
132 }
133
134 #[cfg(feature = "cookies")]
136 pub fn cookies(&self) -> CookieIter<'_> {
137 CookieIter {
138 iter: self.headers().get_all(header::SET_COOKIE),
139 }
140 }
141
142 #[cfg(feature = "cookies")]
147 pub fn add_cookie(&mut self, cookie: &Cookie<'_>) -> Result<(), HttpError> {
148 HeaderValue::from_str(&cookie.to_string())
149 .map(|cookie| self.headers_mut().append(header::SET_COOKIE, cookie))
150 .map_err(Into::into)
151 }
152
153 #[cfg(feature = "cookies")]
171 pub fn add_removal_cookie(&mut self, cookie: &Cookie<'_>) -> Result<(), HttpError> {
172 let mut removal_cookie = cookie.to_owned();
173 removal_cookie.make_removal();
174
175 HeaderValue::from_str(&removal_cookie.to_string())
176 .map(|cookie| self.headers_mut().append(header::SET_COOKIE, cookie))
177 .map_err(Into::into)
178 }
179
180 #[cfg(any(feature = "cookies", feature = "cookies-0_18"))]
187 #[cfg_attr(
188 feature = "cookies",
189 doc = "- For cookie (v0.16), use [`add_removal_cookie()`](Self::add_removal_cookie)."
190 )]
191 #[cfg_attr(
192 feature = "cookies-0_18",
193 doc = "- For cookie (v0.18), use [`add_removal_cookie_0_18()`](Self::add_removal_cookie_0_18)."
194 )]
195 pub fn del_cookie(&mut self, name: &str) -> usize {
196 let headers = self.headers_mut();
197
198 let vals = headers
199 .get_all(header::SET_COOKIE)
200 .map(|v| v.to_owned())
201 .collect::<Vec<_>>();
202
203 headers.remove(header::SET_COOKIE);
204
205 let mut count: usize = 0;
206
207 for v in vals {
208 if let Ok(s) = v.to_str() {
209 if let Ok(c) = Cookie::parse_encoded(s) {
210 if c.name() == name {
211 count += 1;
212 continue;
213 }
214 }
215 }
216
217 headers.append(header::SET_COOKIE, v);
219 }
220
221 count
222 }
223
224 #[inline]
226 pub fn upgrade(&self) -> bool {
227 self.res.upgrade()
228 }
229
230 pub fn keep_alive(&self) -> bool {
232 self.res.keep_alive()
233 }
234
235 #[inline]
237 pub fn extensions(&self) -> Ref<'_, Extensions> {
238 self.res.extensions()
239 }
240
241 #[inline]
243 pub fn extensions_mut(&mut self) -> RefMut<'_, Extensions> {
244 self.res.extensions_mut()
245 }
246
247 #[inline]
249 pub fn body(&self) -> &B {
250 self.res.body()
251 }
252
253 pub fn set_body<B2>(self, body: B2) -> HttpResponse<B2> {
255 HttpResponse {
256 res: self.res.set_body(body),
257 error: self.error,
258 }
259 }
260
261 pub fn into_parts(self) -> (HttpResponse<()>, B) {
267 let (head, body) = self.res.into_parts();
268
269 (
270 HttpResponse {
271 res: head,
272 error: self.error,
273 },
274 body,
275 )
276 }
277
278 pub fn drop_body(self) -> HttpResponse<()> {
280 HttpResponse {
281 res: self.res.drop_body(),
282 error: self.error,
283 }
284 }
285
286 pub fn map_body<F, B2>(self, f: F) -> HttpResponse<B2>
290 where
291 F: FnOnce(&mut ResponseHead, B) -> B2,
292 {
293 HttpResponse {
294 res: self.res.map_body(f),
295 error: self.error,
296 }
297 }
298
299 #[inline]
303 pub fn map_into_left_body<R>(self) -> HttpResponse<EitherBody<B, R>> {
304 self.map_body(|_, body| EitherBody::left(body))
305 }
306
307 #[inline]
311 pub fn map_into_right_body<L>(self) -> HttpResponse<EitherBody<L, B>> {
312 self.map_body(|_, body| EitherBody::right(body))
313 }
314
315 #[inline]
317 pub fn map_into_boxed_body(self) -> HttpResponse<BoxBody>
318 where
319 B: MessageBody + 'static,
320 {
321 self.map_body(|_, body| body.boxed())
322 }
323
324 pub fn into_body(self) -> B {
326 self.res.into_body()
327 }
328}
329
330impl<B> fmt::Debug for HttpResponse<B>
331where
332 B: MessageBody,
333{
334 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
335 f.debug_struct("HttpResponse")
336 .field("error", &self.error)
337 .field("res", &self.res)
338 .finish()
339 }
340}
341
342impl<B> From<Response<B>> for HttpResponse<B> {
343 fn from(res: Response<B>) -> Self {
344 HttpResponse { res, error: None }
345 }
346}
347
348impl From<Error> for HttpResponse {
349 fn from(err: Error) -> Self {
350 HttpResponse::from_error(err)
351 }
352}
353
354impl<B> From<HttpResponse<B>> for Response<B> {
355 fn from(res: HttpResponse<B>) -> Self {
356 res.res
358 }
359}
360
361#[cfg(test)]
365mod response_fut_impl {
366 use std::{
367 future::Future,
368 mem,
369 pin::Pin,
370 task::{Context, Poll},
371 };
372
373 use super::*;
374
375 impl Future for HttpResponse<BoxBody> {
382 type Output = Result<Response<BoxBody>, Error>;
383
384 fn poll(mut self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Self::Output> {
385 if let Some(err) = self.error.take() {
386 return Poll::Ready(Err(err));
387 }
388
389 Poll::Ready(Ok(mem::replace(
390 &mut self.res,
391 Response::new(StatusCode::default()),
392 )))
393 }
394 }
395}
396
397impl<B> Responder for HttpResponse<B>
398where
399 B: MessageBody + 'static,
400{
401 type Body = B;
402
403 #[inline]
404 fn respond_to(self, _: &HttpRequest) -> HttpResponse<Self::Body> {
405 self
406 }
407}
408
409#[cfg(feature = "cookies")]
410pub struct CookieIter<'a> {
411 iter: std::slice::Iter<'a, HeaderValue>,
412}
413
414#[cfg(feature = "cookies")]
415impl<'a> Iterator for CookieIter<'a> {
416 type Item = Cookie<'a>;
417
418 #[inline]
419 fn next(&mut self) -> Option<Cookie<'a>> {
420 for v in self.iter.by_ref() {
421 if let Ok(c) = Cookie::parse_encoded(v.to_str().ok()?) {
422 return Some(c);
423 }
424 }
425 None
426 }
427}
428
429#[cfg(test)]
430mod tests {
431 use static_assertions::assert_impl_all;
432
433 use super::*;
434 use crate::http::header::COOKIE;
435
436 assert_impl_all!(HttpResponse: Responder);
437 assert_impl_all!(HttpResponse<String>: Responder);
438 assert_impl_all!(HttpResponse<&'static str>: Responder);
439 assert_impl_all!(HttpResponse<crate::body::None>: Responder);
440
441 #[test]
442 fn test_debug() {
443 let resp = HttpResponse::Ok()
444 .append_header((COOKIE, HeaderValue::from_static("cookie1=value1; ")))
445 .append_header((COOKIE, HeaderValue::from_static("cookie2=value2; ")))
446 .finish();
447 let dbg = format!("{:?}", resp);
448 assert!(dbg.contains("HttpResponse"));
449 }
450}
451
452#[cfg(test)]
453#[cfg(feature = "cookies")]
454mod cookie_tests {
455 use super::*;
456
457 #[test]
458 fn removal_cookies() {
459 let mut res = HttpResponse::Ok().finish();
460 let cookie = Cookie::new("foo", "");
461 res.add_removal_cookie(&cookie).unwrap();
462 let set_cookie_hdr = res.headers().get(header::SET_COOKIE).unwrap();
463 assert_eq!(
464 &set_cookie_hdr.as_bytes()[..25],
465 &b"foo=; Max-Age=0; Expires="[..],
466 "unexpected set-cookie value: {:?}",
467 set_cookie_hdr.to_str()
468 );
469 }
470}