Skip to main content

actix_web/
service.rs

1use std::{
2    cell::{Ref, RefMut},
3    fmt, net,
4    rc::Rc,
5};
6
7use actix_http::{
8    body::{BoxBody, EitherBody, MessageBody},
9    header::HeaderMap,
10    BoxedPayloadStream, Extensions, HttpMessage, Method, Payload, RequestHead, Response,
11    ResponseHead, StatusCode, Uri, Version,
12};
13use actix_router::{IntoPatterns, Path, Patterns, Resource, ResourceDef, Url};
14use actix_service::{
15    boxed::{BoxService, BoxServiceFactory},
16    IntoServiceFactory, ServiceFactory,
17};
18#[cfg(feature = "cookies")]
19use cookie::{Cookie, ParseError as CookieParseError};
20
21use crate::{
22    config::{AppConfig, AppService},
23    dev::ensure_leading_slash,
24    guard::{Guard, GuardContext},
25    info::ConnectionInfo,
26    rmap::ResourceMap,
27    Error, FromRequest, HttpRequest, HttpResponse,
28};
29
30pub(crate) type BoxedHttpService = BoxService<ServiceRequest, ServiceResponse<BoxBody>, Error>;
31pub(crate) type BoxedHttpServiceFactory =
32    BoxServiceFactory<(), ServiceRequest, ServiceResponse<BoxBody>, Error, ()>;
33
34pub trait HttpServiceFactory {
35    fn register(self, config: &mut AppService);
36}
37
38impl<T: HttpServiceFactory> HttpServiceFactory for Vec<T> {
39    fn register(self, config: &mut AppService) {
40        self.into_iter()
41            .for_each(|factory| factory.register(config));
42    }
43}
44
45pub(crate) trait AppServiceFactory {
46    fn register(&mut self, config: &mut AppService);
47}
48
49pub(crate) struct ServiceFactoryWrapper<T> {
50    factory: Option<T>,
51}
52
53impl<T> ServiceFactoryWrapper<T> {
54    pub fn new(factory: T) -> Self {
55        Self {
56            factory: Some(factory),
57        }
58    }
59}
60
61impl<T> AppServiceFactory for ServiceFactoryWrapper<T>
62where
63    T: HttpServiceFactory,
64{
65    fn register(&mut self, config: &mut AppService) {
66        if let Some(item) = self.factory.take() {
67            item.register(config)
68        }
69    }
70}
71
72/// A service level request wrapper.
73///
74/// Allows mutable access to request's internal structures.
75pub struct ServiceRequest {
76    req: HttpRequest,
77    payload: Payload,
78}
79
80impl ServiceRequest {
81    /// Construct `ServiceRequest` from parts.
82    pub(crate) fn new(req: HttpRequest, payload: Payload) -> Self {
83        Self { req, payload }
84    }
85
86    /// Deconstruct `ServiceRequest` into inner parts.
87    #[inline]
88    pub fn into_parts(self) -> (HttpRequest, Payload) {
89        (self.req, self.payload)
90    }
91
92    /// Returns mutable accessors to inner parts.
93    #[inline]
94    pub fn parts_mut(&mut self) -> (&mut HttpRequest, &mut Payload) {
95        (&mut self.req, &mut self.payload)
96    }
97
98    /// Returns immutable accessors to inner parts.
99    #[inline]
100    pub fn parts(&self) -> (&HttpRequest, &Payload) {
101        (&self.req, &self.payload)
102    }
103
104    /// Returns immutable accessor to inner [`HttpRequest`].
105    #[inline]
106    pub fn request(&self) -> &HttpRequest {
107        &self.req
108    }
109
110    /// Derives a type from this request using an [extractor](crate::FromRequest).
111    ///
112    /// Returns the `T` extractor's `Future` type which can be `await`ed. This is particularly handy
113    /// when you want to use an extractor in a middleware implementation.
114    ///
115    /// # Examples
116    /// ```
117    /// use actix_web::{
118    ///     dev::{ServiceRequest, ServiceResponse},
119    ///     web::Path, Error
120    /// };
121    ///
122    /// async fn my_helper(mut srv_req: ServiceRequest) -> Result<ServiceResponse, Error> {
123    ///     let path = srv_req.extract::<Path<(String, u32)>>().await?;
124    ///     // [...]
125    /// #   todo!()
126    /// }
127    /// ```
128    pub fn extract<T>(&mut self) -> <T as FromRequest>::Future
129    where
130        T: FromRequest,
131    {
132        T::from_request(&self.req, &mut self.payload)
133    }
134
135    /// Construct request from parts.
136    pub fn from_parts(req: HttpRequest, payload: Payload) -> Self {
137        #[cfg(debug_assertions)]
138        if Rc::strong_count(&req.inner) > 1 {
139            log::warn!("Cloning an `HttpRequest` might cause panics.");
140        }
141
142        Self { req, payload }
143    }
144
145    /// Construct `ServiceRequest` with no payload from given `HttpRequest`.
146    #[inline]
147    pub fn from_request(req: HttpRequest) -> Self {
148        ServiceRequest {
149            req,
150            payload: Payload::None,
151        }
152    }
153
154    /// Create `ServiceResponse` from this request and given response.
155    #[inline]
156    pub fn into_response<B, R: Into<Response<B>>>(self, res: R) -> ServiceResponse<B> {
157        let res = HttpResponse::from(res.into());
158        ServiceResponse::new(self.req, res)
159    }
160
161    /// Create `ServiceResponse` from this request and given error.
162    #[inline]
163    pub fn error_response<E: Into<Error>>(self, err: E) -> ServiceResponse {
164        let res = HttpResponse::from_error(err.into());
165        ServiceResponse::new(self.req, res)
166    }
167
168    /// Returns a reference to the request head.
169    #[inline]
170    pub fn head(&self) -> &RequestHead {
171        self.req.head()
172    }
173
174    /// Returns a mutable reference to the request head.
175    #[inline]
176    pub fn head_mut(&mut self) -> &mut RequestHead {
177        self.req.head_mut()
178    }
179
180    /// Returns the request URI.
181    #[inline]
182    pub fn uri(&self) -> &Uri {
183        &self.head().uri
184    }
185
186    /// Returns the request method.
187    #[inline]
188    pub fn method(&self) -> &Method {
189        &self.head().method
190    }
191
192    /// Returns the request version.
193    #[inline]
194    pub fn version(&self) -> Version {
195        self.head().version
196    }
197
198    /// Returns a reference to request headers.
199    #[inline]
200    pub fn headers(&self) -> &HeaderMap {
201        &self.head().headers
202    }
203
204    /// Returns a mutable reference to request headers.
205    #[inline]
206    pub fn headers_mut(&mut self) -> &mut HeaderMap {
207        &mut self.head_mut().headers
208    }
209
210    /// Returns request path.
211    #[inline]
212    pub fn path(&self) -> &str {
213        self.head().uri.path()
214    }
215
216    /// Counterpart to [`HttpRequest::query_string`].
217    #[inline]
218    pub fn query_string(&self) -> &str {
219        self.req.query_string()
220    }
221
222    /// Returns peer's socket address.
223    ///
224    /// See [`HttpRequest::peer_addr`] for more details.
225    ///
226    /// [`HttpRequest::peer_addr`]: crate::HttpRequest::peer_addr
227    #[inline]
228    pub fn peer_addr(&self) -> Option<net::SocketAddr> {
229        self.head().peer_addr
230    }
231
232    /// Returns a reference to connection info.
233    #[inline]
234    pub fn connection_info(&self) -> Ref<'_, ConnectionInfo> {
235        self.req.connection_info()
236    }
237
238    /// Counterpart to [`HttpRequest::match_info`].
239    #[inline]
240    pub fn match_info(&self) -> &Path<Url> {
241        self.req.match_info()
242    }
243
244    /// Returns a mutable reference to the path match information.
245    #[inline]
246    pub fn match_info_mut(&mut self) -> &mut Path<Url> {
247        self.req.match_info_mut()
248    }
249
250    /// Counterpart to [`HttpRequest::match_name`].
251    #[inline]
252    pub fn match_name(&self) -> Option<&str> {
253        self.req.match_name()
254    }
255
256    /// Counterpart to [`HttpRequest::match_pattern`].
257    #[inline]
258    pub fn match_pattern(&self) -> Option<String> {
259        self.req.match_pattern()
260    }
261
262    /// Returns a reference to the application's resource map.
263    /// Counterpart to [`HttpRequest::resource_map`].
264    #[inline]
265    pub fn resource_map(&self) -> &ResourceMap {
266        self.req.resource_map()
267    }
268
269    /// Counterpart to [`HttpRequest::app_config`].
270    #[inline]
271    pub fn app_config(&self) -> &AppConfig {
272        self.req.app_config()
273    }
274
275    /// Counterpart to [`HttpRequest::app_data`].
276    #[inline]
277    pub fn app_data<T: 'static>(&self) -> Option<&T> {
278        for container in self.req.inner.app_data.iter().rev() {
279            if let Some(data) = container.get::<T>() {
280                return Some(data);
281            }
282        }
283
284        None
285    }
286
287    /// Counterpart to [`HttpRequest::conn_data`].
288    #[inline]
289    pub fn conn_data<T: 'static>(&self) -> Option<&T> {
290        self.req.conn_data()
291    }
292
293    /// Returns request cookies with percent-decoded names and values using cookie (v0.18).
294    #[cfg(feature = "cookies-0_18")]
295    pub fn cookies_0_18(&self) -> Result<Vec<cookie_0_18::Cookie<'_>>, cookie_0_18::ParseError> {
296        self.req.cookies_0_18()
297    }
298
299    /// Returns request cookies with raw names and values using cookie (v0.18).
300    #[cfg(feature = "cookies-0_18")]
301    pub fn cookies_raw_0_18(
302        &self,
303    ) -> Result<Vec<cookie_0_18::Cookie<'_>>, cookie_0_18::ParseError> {
304        self.req.cookies_raw_0_18()
305    }
306
307    /// Returns the named request cookie with percent-decoded names and values using cookie (v0.18).
308    #[cfg(feature = "cookies-0_18")]
309    pub fn cookie_0_18(&self, name: &str) -> Option<cookie_0_18::Cookie<'_>> {
310        self.req.cookie_0_18(name)
311    }
312
313    /// Returns the named request cookie with raw names and values using cookie (v0.18).
314    #[cfg(feature = "cookies-0_18")]
315    pub fn cookie_raw_0_18(&self, name: &str) -> Option<cookie_0_18::Cookie<'_>> {
316        self.req.cookie_raw_0_18(name)
317    }
318
319    /// Return request cookies.
320    #[cfg(feature = "cookies")]
321    #[inline]
322    pub fn cookies(&self) -> Result<Ref<'_, Vec<Cookie<'static>>>, CookieParseError> {
323        self.req.cookies()
324    }
325
326    /// Return request cookies **without** percent-decoding their names and values.
327    #[cfg(feature = "cookies")]
328    #[inline]
329    pub fn cookies_raw(&self) -> Result<Ref<'_, Vec<Cookie<'static>>>, CookieParseError> {
330        self.req.cookies_raw()
331    }
332
333    /// Return request cookie.
334    #[cfg(feature = "cookies")]
335    #[inline]
336    pub fn cookie(&self, name: &str) -> Option<Cookie<'static>> {
337        self.req.cookie(name)
338    }
339
340    /// Return request cookie **without** percent-decoding its name and value.
341    #[cfg(feature = "cookies")]
342    #[inline]
343    pub fn cookie_raw(&self, name: &str) -> Option<Cookie<'static>> {
344        self.req.cookie_raw(name)
345    }
346
347    /// Set request payload.
348    #[inline]
349    pub fn set_payload(&mut self, payload: Payload) {
350        self.payload = payload;
351    }
352
353    /// Add data container to request's resolution set.
354    ///
355    /// In middleware, prefer [`extensions_mut`](ServiceRequest::extensions_mut) for request-local
356    /// data since it is assumed that the same app data is presented for every request.
357    pub fn add_data_container(&mut self, extensions: Rc<Extensions>) {
358        Rc::get_mut(&mut (self.req).inner)
359            .unwrap()
360            .app_data
361            .push(extensions);
362    }
363
364    #[inline]
365    pub(crate) fn push_resource_id(&mut self, id: u16) {
366        self.req.push_resource_id(id);
367    }
368
369    #[inline]
370    pub(crate) fn mark_resource_path(&mut self, is_matched: bool) {
371        self.req.mark_resource_path(is_matched);
372    }
373
374    #[inline]
375    pub(crate) fn resource_id_path(&self) -> &[u16] {
376        self.req.resource_path()
377    }
378
379    /// Creates a context object for use with a routing [guard](crate::guard).
380    #[inline]
381    pub fn guard_ctx(&self) -> GuardContext<'_> {
382        GuardContext { req: self }
383    }
384}
385
386impl Resource for ServiceRequest {
387    type Path = Url;
388
389    #[inline]
390    fn resource_path(&mut self) -> &mut Path<Self::Path> {
391        self.match_info_mut()
392    }
393}
394
395impl HttpMessage for ServiceRequest {
396    type Stream = BoxedPayloadStream;
397
398    #[inline]
399    fn headers(&self) -> &HeaderMap {
400        &self.head().headers
401    }
402
403    #[inline]
404    fn extensions(&self) -> Ref<'_, Extensions> {
405        self.req.extensions()
406    }
407
408    #[inline]
409    fn extensions_mut(&self) -> RefMut<'_, Extensions> {
410        self.req.extensions_mut()
411    }
412
413    #[inline]
414    fn take_payload(&mut self) -> Payload<Self::Stream> {
415        self.payload.take()
416    }
417}
418
419impl fmt::Debug for ServiceRequest {
420    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
421        writeln!(
422            f,
423            "\nServiceRequest {:?} {}:{}",
424            self.head().version,
425            self.head().method,
426            self.path()
427        )?;
428        if !self.query_string().is_empty() {
429            writeln!(f, "  query: ?{:?}", self.query_string())?;
430        }
431        if !self.match_info().is_empty() {
432            writeln!(f, "  params: {:?}", self.match_info())?;
433        }
434        writeln!(f, "  headers:")?;
435        for (key, val) in self.headers().iter() {
436            writeln!(f, "    {:?}: {:?}", key, val)?;
437        }
438        Ok(())
439    }
440}
441
442/// A service level response wrapper.
443pub struct ServiceResponse<B = BoxBody> {
444    request: HttpRequest,
445    response: HttpResponse<B>,
446}
447
448impl ServiceResponse<BoxBody> {
449    /// Create service response from the error
450    pub fn from_err<E: Into<Error>>(err: E, request: HttpRequest) -> Self {
451        let response = HttpResponse::from_error(err);
452        ServiceResponse { request, response }
453    }
454}
455
456impl<B> ServiceResponse<B> {
457    /// Create service response instance
458    pub fn new(request: HttpRequest, response: HttpResponse<B>) -> Self {
459        ServiceResponse { request, response }
460    }
461
462    /// Create service response for error
463    #[inline]
464    pub fn error_response<E: Into<Error>>(self, err: E) -> ServiceResponse {
465        ServiceResponse::from_err(err, self.request)
466    }
467
468    /// Create service response
469    #[inline]
470    pub fn into_response<B1>(self, response: HttpResponse<B1>) -> ServiceResponse<B1> {
471        ServiceResponse::new(self.request, response)
472    }
473
474    /// Returns reference to original request.
475    #[inline]
476    pub fn request(&self) -> &HttpRequest {
477        &self.request
478    }
479
480    /// Returns reference to response.
481    #[inline]
482    pub fn response(&self) -> &HttpResponse<B> {
483        &self.response
484    }
485
486    /// Returns mutable reference to response.
487    #[inline]
488    pub fn response_mut(&mut self) -> &mut HttpResponse<B> {
489        &mut self.response
490    }
491
492    /// Returns response status code.
493    #[inline]
494    pub fn status(&self) -> StatusCode {
495        self.response.status()
496    }
497
498    /// Returns response's headers.
499    #[inline]
500    pub fn headers(&self) -> &HeaderMap {
501        self.response.headers()
502    }
503
504    /// Returns mutable response's headers.
505    #[inline]
506    pub fn headers_mut(&mut self) -> &mut HeaderMap {
507        self.response.headers_mut()
508    }
509
510    /// Destructures `ServiceResponse` into request and response components.
511    #[inline]
512    pub fn into_parts(self) -> (HttpRequest, HttpResponse<B>) {
513        (self.request, self.response)
514    }
515
516    /// Map the current body type to another using a closure. Returns a new response.
517    ///
518    /// Closure receives the response head and the current body type.
519    #[inline]
520    pub fn map_body<F, B2>(self, f: F) -> ServiceResponse<B2>
521    where
522        F: FnOnce(&mut ResponseHead, B) -> B2,
523    {
524        let response = self.response.map_body(f);
525
526        ServiceResponse {
527            response,
528            request: self.request,
529        }
530    }
531
532    #[inline]
533    pub fn map_into_left_body<R>(self) -> ServiceResponse<EitherBody<B, R>> {
534        self.map_body(|_, body| EitherBody::left(body))
535    }
536
537    #[inline]
538    pub fn map_into_right_body<L>(self) -> ServiceResponse<EitherBody<L, B>> {
539        self.map_body(|_, body| EitherBody::right(body))
540    }
541
542    #[inline]
543    pub fn map_into_boxed_body(self) -> ServiceResponse<BoxBody>
544    where
545        B: MessageBody + 'static,
546    {
547        self.map_body(|_, body| body.boxed())
548    }
549
550    /// Consumes the response and returns its body.
551    #[inline]
552    pub fn into_body(self) -> B {
553        self.response.into_body()
554    }
555}
556
557impl<B> From<ServiceResponse<B>> for HttpResponse<B> {
558    fn from(res: ServiceResponse<B>) -> HttpResponse<B> {
559        res.response
560    }
561}
562
563impl<B> From<ServiceResponse<B>> for Response<B> {
564    fn from(res: ServiceResponse<B>) -> Response<B> {
565        res.response.into()
566    }
567}
568
569impl<B> fmt::Debug for ServiceResponse<B>
570where
571    B: MessageBody,
572    B::Error: Into<Error>,
573{
574    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
575        let res = writeln!(
576            f,
577            "\nServiceResponse {:?} {}{}",
578            self.response.head().version,
579            self.response.head().status,
580            self.response.head().reason.unwrap_or(""),
581        );
582        let _ = writeln!(f, "  headers:");
583        for (key, val) in self.response.head().headers.iter() {
584            let _ = writeln!(f, "    {:?}: {:?}", key, val);
585        }
586        let _ = writeln!(f, "  body: {:?}", self.response.body().size());
587        res
588    }
589}
590
591pub struct WebService {
592    rdef: Patterns,
593    name: Option<String>,
594    guards: Vec<Box<dyn Guard>>,
595}
596
597impl WebService {
598    /// Create new `WebService` instance.
599    pub fn new<T: IntoPatterns>(path: T) -> Self {
600        WebService {
601            rdef: path.patterns(),
602            name: None,
603            guards: Vec::new(),
604        }
605    }
606
607    /// Set service name.
608    ///
609    /// Name is used for URL generation.
610    pub fn name(mut self, name: &str) -> Self {
611        self.name = Some(name.to_string());
612        self
613    }
614
615    /// Add match guard to a web service.
616    ///
617    /// ```
618    /// use actix_web::{web, guard, dev, App, Error, HttpResponse};
619    ///
620    /// async fn index(req: dev::ServiceRequest) -> Result<dev::ServiceResponse, Error> {
621    ///     Ok(req.into_response(HttpResponse::Ok().finish()))
622    /// }
623    ///
624    /// let app = App::new()
625    ///     .service(
626    ///         web::service("/app")
627    ///             .guard(guard::Header("content-type", "text/plain"))
628    ///             .finish(index)
629    ///     );
630    /// ```
631    pub fn guard<G: Guard + 'static>(mut self, guard: G) -> Self {
632        self.guards.push(Box::new(guard));
633        self
634    }
635
636    /// Set a service factory implementation and generate web service.
637    pub fn finish<T, F>(self, service: F) -> impl HttpServiceFactory
638    where
639        F: IntoServiceFactory<T, ServiceRequest>,
640        T: ServiceFactory<
641                ServiceRequest,
642                Config = (),
643                Response = ServiceResponse,
644                Error = Error,
645                InitError = (),
646            > + 'static,
647    {
648        WebServiceImpl {
649            srv: service.into_factory(),
650            rdef: self.rdef,
651            name: self.name,
652            guards: self.guards,
653        }
654    }
655}
656
657struct WebServiceImpl<T> {
658    srv: T,
659    rdef: Patterns,
660    name: Option<String>,
661    guards: Vec<Box<dyn Guard>>,
662}
663
664impl<T> HttpServiceFactory for WebServiceImpl<T>
665where
666    T: ServiceFactory<
667            ServiceRequest,
668            Config = (),
669            Response = ServiceResponse,
670            Error = Error,
671            InitError = (),
672        > + 'static,
673{
674    fn register(mut self, config: &mut AppService) {
675        let guards = if self.guards.is_empty() {
676            None
677        } else {
678            Some(std::mem::take(&mut self.guards))
679        };
680
681        let mut rdef = if config.is_root() || !self.rdef.is_empty() {
682            ResourceDef::new(ensure_leading_slash(self.rdef))
683        } else {
684            ResourceDef::new(self.rdef)
685        };
686
687        if let Some(ref name) = self.name {
688            rdef.set_name(name);
689        }
690
691        config.register_service(rdef, guards, self.srv, None)
692    }
693}
694
695/// Macro to help register different types of services at the same time.
696///
697/// The max number of services that can be grouped together is 12 and all must implement the
698/// [`HttpServiceFactory`] trait.
699///
700/// # Examples
701/// ```
702/// use actix_web::{services, web, App};
703///
704/// let services = services![
705///     web::resource("/test2").to(|| async { "test2" }),
706///     web::scope("/test3").route("/", web::get().to(|| async { "test3" }))
707/// ];
708///
709/// let app = App::new().service(services);
710///
711/// // services macro just convert multiple services to a tuple.
712/// // below would also work without importing the macro.
713/// let app = App::new().service((
714///     web::resource("/test2").to(|| async { "test2" }),
715///     web::scope("/test3").route("/", web::get().to(|| async { "test3" }))
716/// ));
717/// ```
718#[macro_export]
719macro_rules! services {
720    () => {()};
721    ($($x:expr),+ $(,)?) => {
722        ($($x,)+)
723    }
724}
725
726/// HttpServiceFactory trait impl for tuples
727macro_rules! service_tuple ({ $($T:ident)+ } => {
728    impl<$($T: HttpServiceFactory),+> HttpServiceFactory for ($($T,)+) {
729        #[allow(non_snake_case)]
730        fn register(self, config: &mut AppService) {
731            let ($($T,)*) = self;
732            $($T.register(config);)+
733        }
734    }
735});
736
737service_tuple! { A }
738service_tuple! { A B }
739service_tuple! { A B C }
740service_tuple! { A B C D }
741service_tuple! { A B C D E }
742service_tuple! { A B C D E F }
743service_tuple! { A B C D E F G }
744service_tuple! { A B C D E F G H }
745service_tuple! { A B C D E F G H I }
746service_tuple! { A B C D E F G H I J }
747service_tuple! { A B C D E F G H I J K }
748service_tuple! { A B C D E F G H I J K L }
749
750#[cfg(test)]
751mod tests {
752    use std::future::ready;
753
754    use actix_service::Service;
755
756    use super::*;
757    use crate::{
758        guard, http,
759        test::{self, init_service, TestRequest},
760        web, App,
761    };
762
763    #[tokio::test(flavor = "local")]
764    async fn test_service() {
765        let srv =
766            init_service(
767                App::new().service(web::service("/test").name("test").finish(
768                    |req: ServiceRequest| ready(Ok(req.into_response(HttpResponse::Ok().finish()))),
769                )),
770            )
771            .await;
772        let req = TestRequest::with_uri("/test").to_request();
773        let resp = srv.call(req).await.unwrap();
774        assert_eq!(resp.status(), http::StatusCode::OK);
775
776        let srv = init_service(
777            App::new().service(web::service("/test").guard(guard::Get()).finish(
778                |req: ServiceRequest| ready(Ok(req.into_response(HttpResponse::Ok().finish()))),
779            )),
780        )
781        .await;
782        let req = TestRequest::with_uri("/test")
783            .method(http::Method::PUT)
784            .to_request();
785        let resp = srv.call(req).await.unwrap();
786        assert_eq!(resp.status(), http::StatusCode::METHOD_NOT_ALLOWED);
787    }
788
789    // allow deprecated App::data
790    #[allow(deprecated)]
791    #[tokio::test(flavor = "local")]
792    async fn test_service_data() {
793        let srv = init_service(
794            App::new()
795                .data(42u32)
796                .service(
797                    web::service("/test")
798                        .name("test")
799                        .finish(|req: ServiceRequest| {
800                            assert_eq!(req.app_data::<web::Data<u32>>().unwrap().as_ref(), &42);
801                            ready(Ok(req.into_response(HttpResponse::Ok().finish())))
802                        }),
803                ),
804        )
805        .await;
806        let req = TestRequest::with_uri("/test").to_request();
807        let resp = srv.call(req).await.unwrap();
808        assert_eq!(resp.status(), http::StatusCode::OK);
809    }
810
811    #[test]
812    fn test_fmt_debug() {
813        let req = TestRequest::get()
814            .uri("/index.html?test=1")
815            .insert_header(("x-test", "111"))
816            .to_srv_request();
817        let s = format!("{:?}", req);
818        assert!(s.contains("ServiceRequest"));
819        assert!(s.contains("test=1"));
820        assert!(s.contains("x-test"));
821
822        let res = HttpResponse::Ok().insert_header(("x-test", "111")).finish();
823        let res = TestRequest::post()
824            .uri("/index.html?test=1")
825            .to_srv_response(res);
826
827        let s = format!("{:?}", res);
828        assert!(s.contains("ServiceResponse"));
829        assert!(s.contains("x-test"));
830    }
831
832    #[tokio::test(flavor = "local")]
833    async fn test_services_macro() {
834        let scoped = services![
835            web::service("/scoped_test1").name("scoped_test1").finish(
836                |req: ServiceRequest| async { Ok(req.into_response(HttpResponse::Ok().finish())) }
837            ),
838            web::resource("/scoped_test2").to(|| async { "test2" }),
839        ];
840
841        let services = services![
842            web::service("/test1")
843                .name("test")
844                .finish(|req: ServiceRequest| async {
845                    Ok(req.into_response(HttpResponse::Ok().finish()))
846                }),
847            web::resource("/test2").to(|| async { "test2" }),
848            web::scope("/test3").service(scoped)
849        ];
850
851        let srv = init_service(App::new().service(services)).await;
852
853        let req = TestRequest::with_uri("/test1").to_request();
854        let resp = srv.call(req).await.unwrap();
855        assert_eq!(resp.status(), http::StatusCode::OK);
856
857        let req = TestRequest::with_uri("/test2").to_request();
858        let resp = srv.call(req).await.unwrap();
859        assert_eq!(resp.status(), http::StatusCode::OK);
860
861        let req = TestRequest::with_uri("/test3/scoped_test1").to_request();
862        let resp = srv.call(req).await.unwrap();
863        assert_eq!(resp.status(), http::StatusCode::OK);
864
865        let req = TestRequest::with_uri("/test3/scoped_test2").to_request();
866        let resp = srv.call(req).await.unwrap();
867        assert_eq!(resp.status(), http::StatusCode::OK);
868    }
869
870    #[tokio::test(flavor = "local")]
871    async fn test_services_vec() {
872        let services = vec![
873            web::resource("/test1").to(|| async { "test1" }),
874            web::resource("/test2").to(|| async { "test2" }),
875        ];
876
877        let scoped = vec![
878            web::resource("/scoped_test1").to(|| async { "test1" }),
879            web::resource("/scoped_test2").to(|| async { "test2" }),
880        ];
881
882        let srv = init_service(
883            App::new()
884                .service(services)
885                .service(web::scope("/test3").service(scoped)),
886        )
887        .await;
888
889        let req = TestRequest::with_uri("/test1").to_request();
890        let resp = srv.call(req).await.unwrap();
891        assert_eq!(resp.status(), http::StatusCode::OK);
892
893        let req = TestRequest::with_uri("/test2").to_request();
894        let resp = srv.call(req).await.unwrap();
895        assert_eq!(resp.status(), http::StatusCode::OK);
896
897        let req = TestRequest::with_uri("/test3/scoped_test1").to_request();
898        let resp = srv.call(req).await.unwrap();
899        assert_eq!(resp.status(), http::StatusCode::OK);
900
901        let req = TestRequest::with_uri("/test3/scoped_test2").to_request();
902        let resp = srv.call(req).await.unwrap();
903        assert_eq!(resp.status(), http::StatusCode::OK);
904    }
905
906    #[tokio::test(flavor = "local")]
907    #[should_panic(expected = "called `Option::unwrap()` on a `None` value")]
908    async fn cloning_request_panics() {
909        async fn index(_name: web::Path<(String,)>) -> &'static str {
910            ""
911        }
912
913        let app = test::init_service(
914            App::new()
915                .wrap_fn(|req, svc| {
916                    let (req, pl) = req.into_parts();
917                    let _req2 = req.clone();
918                    let req = ServiceRequest::from_parts(req, pl);
919                    svc.call(req)
920                })
921                .route("/", web::get().to(|| async { "" }))
922                .service(web::resource("/resource1/{name}/index.html").route(web::get().to(index))),
923        )
924        .await;
925
926        let req = test::TestRequest::default().to_request();
927        let _res = test::call_service(&app, req).await;
928    }
929
930    #[test]
931    fn define_services_macro_with_multiple_arguments() {
932        let result = services!(1, 2, 3);
933        assert_eq!(result, (1, 2, 3));
934    }
935
936    #[test]
937    fn define_services_macro_with_single_argument() {
938        let result = services!(1);
939        assert_eq!(result, (1,));
940    }
941
942    #[test]
943    fn define_services_macro_with_no_arguments() {
944        let result = services!();
945        let () = result;
946    }
947
948    #[test]
949    fn define_services_macro_with_trailing_comma() {
950        let result = services!(1, 2, 3,);
951        assert_eq!(result, (1, 2, 3));
952    }
953
954    #[test]
955    fn define_services_macro_with_comments_in_arguments() {
956        let result = services!(
957            1, // First comment
958            2, // Second comment
959            3  // Third comment
960        );
961
962        // Assert that comments are ignored and it correctly returns a tuple.
963        assert_eq!(result, (1, 2, 3));
964    }
965}