actix_web/response/
customize_responder.rs1use actix_http::{
2 body::EitherBody,
3 error::HttpError,
4 header::{HeaderMap, TryIntoHeaderPair},
5 StatusCode,
6};
7
8use crate::{HttpRequest, HttpResponse, Responder};
9
10pub struct CustomizeResponder<R> {
14 inner: CustomizeResponderInner<R>,
15 error: Option<HttpError>,
16}
17
18struct CustomizeResponderInner<R> {
19 responder: R,
20 status: Option<StatusCode>,
21 override_headers: HeaderMap,
22 append_headers: HeaderMap,
23}
24
25impl<R: Responder> CustomizeResponder<R> {
26 pub(crate) fn new(responder: R) -> Self {
27 CustomizeResponder {
28 inner: CustomizeResponderInner {
29 responder,
30 status: None,
31 override_headers: HeaderMap::new(),
32 append_headers: HeaderMap::new(),
33 },
34 error: None,
35 }
36 }
37
38 pub fn with_status(mut self, status: StatusCode) -> Self {
51 if let Some(inner) = self.inner() {
52 inner.status = Some(status);
53 }
54
55 self
56 }
57
58 pub fn insert_header(mut self, header: impl TryIntoHeaderPair) -> Self {
80 if let Some(inner) = self.inner() {
81 match header.try_into_pair() {
82 Ok((key, value)) => {
83 inner.override_headers.insert(key, value);
84 }
85 Err(err) => self.error = Some(err.into()),
86 };
87 }
88
89 self
90 }
91
92 pub fn append_header(mut self, header: impl TryIntoHeaderPair) -> Self {
112 if let Some(inner) = self.inner() {
113 match header.try_into_pair() {
114 Ok((key, value)) => {
115 inner.append_headers.append(key, value);
116 }
117 Err(err) => self.error = Some(err.into()),
118 };
119 }
120
121 self
122 }
123
124 #[doc(hidden)]
125 #[deprecated(since = "4.0.0", note = "Renamed to `insert_header`.")]
126 pub fn with_header(self, header: impl TryIntoHeaderPair) -> Self
127 where
128 Self: Sized,
129 {
130 self.insert_header(header)
131 }
132
133 fn inner(&mut self) -> Option<&mut CustomizeResponderInner<R>> {
134 if self.error.is_some() {
135 None
136 } else {
137 Some(&mut self.inner)
138 }
139 }
140
141 #[cfg(feature = "cookies-0_18")]
143 pub fn add_cookie_0_18(self, cookie: &cookie_0_18::Cookie<'_>) -> Self {
144 self.append_header((actix_http::header::SET_COOKIE, cookie.to_string()))
145 }
146
147 #[cfg(feature = "cookies")]
153 pub fn add_cookie(mut self, cookie: &crate::cookie::Cookie<'_>) -> Self {
154 use actix_http::header::{TryIntoHeaderValue as _, SET_COOKIE};
155
156 if let Some(inner) = self.inner() {
157 match cookie.to_string().try_into_value() {
158 Ok(val) => {
159 inner.append_headers.append(SET_COOKIE, val);
160 }
161 Err(err) => {
162 self.error = Some(err.into());
163 }
164 }
165 }
166
167 self
168 }
169}
170
171impl<T> Responder for CustomizeResponder<T>
172where
173 T: Responder,
174{
175 type Body = EitherBody<T::Body>;
176
177 fn respond_to(self, req: &HttpRequest) -> HttpResponse<Self::Body> {
178 if let Some(err) = self.error {
179 return HttpResponse::from_error(err).map_into_right_body();
180 }
181
182 let mut res = self.inner.responder.respond_to(req);
183
184 if let Some(status) = self.inner.status {
185 *res.status_mut() = status;
186 }
187
188 for (k, v) in self.inner.override_headers {
189 res.headers_mut().insert(k, v);
190 }
191
192 for (k, v) in self.inner.append_headers {
193 res.headers_mut().append(k, v);
194 }
195
196 res.map_into_left_body()
197 }
198}
199
200#[cfg(test)]
201mod tests {
202 use actix_http::body::to_bytes;
203 use bytes::Bytes;
204
205 use super::*;
206 use crate::{
207 cookie::Cookie,
208 http::header::{HeaderValue, CONTENT_TYPE},
209 test::TestRequest,
210 };
211
212 #[tokio::test(flavor = "local")]
213 async fn customize_responder() {
214 let req = TestRequest::default().to_http_request();
215 let res = "test"
216 .to_string()
217 .customize()
218 .with_status(StatusCode::BAD_REQUEST)
219 .respond_to(&req);
220
221 assert_eq!(res.status(), StatusCode::BAD_REQUEST);
222 assert_eq!(
223 to_bytes(res.into_body()).await.unwrap(),
224 Bytes::from_static(b"test"),
225 );
226
227 let res = "test"
228 .to_string()
229 .customize()
230 .insert_header(("content-type", "json"))
231 .respond_to(&req);
232
233 assert_eq!(res.status(), StatusCode::OK);
234 assert_eq!(
235 res.headers().get(CONTENT_TYPE).unwrap(),
236 HeaderValue::from_static("json")
237 );
238 assert_eq!(
239 to_bytes(res.into_body()).await.unwrap(),
240 Bytes::from_static(b"test"),
241 );
242
243 let res = "test"
244 .to_string()
245 .customize()
246 .add_cookie(&Cookie::new("name", "value"))
247 .respond_to(&req);
248
249 assert!(res.status().is_success());
250 assert_eq!(
251 res.cookies().collect::<Vec<Cookie<'_>>>(),
252 vec![Cookie::new("name", "value")],
253 );
254 assert_eq!(
255 to_bytes(res.into_body()).await.unwrap(),
256 Bytes::from_static(b"test"),
257 );
258 }
259
260 #[tokio::test(flavor = "local")]
261 async fn tuple_responder_with_status_code() {
262 let req = TestRequest::default().to_http_request();
263 let res = ("test".to_string(), StatusCode::BAD_REQUEST).respond_to(&req);
264 assert_eq!(res.status(), StatusCode::BAD_REQUEST);
265 assert_eq!(
266 to_bytes(res.into_body()).await.unwrap(),
267 Bytes::from_static(b"test"),
268 );
269
270 let req = TestRequest::default().to_http_request();
271 let res = ("test".to_string(), StatusCode::OK)
272 .customize()
273 .insert_header((CONTENT_TYPE, mime::APPLICATION_JSON))
274 .respond_to(&req);
275 assert_eq!(res.status(), StatusCode::OK);
276 assert_eq!(
277 res.headers().get(CONTENT_TYPE).unwrap(),
278 HeaderValue::from_static("application/json")
279 );
280 assert_eq!(
281 to_bytes(res.into_body()).await.unwrap(),
282 Bytes::from_static(b"test"),
283 );
284 }
285}