1
0
Fork 0
mirror of https://github.com/actix/actix-web.git synced 2024-05-19 16:58:14 +00:00
actix-web/actix-web/src/service.rs

874 lines
25 KiB
Rust
Raw Normal View History

2021-12-04 19:40:47 +00:00
use std::{
cell::{Ref, RefMut},
fmt, net,
rc::Rc,
};
2019-03-02 06:51:32 +00:00
use actix_http::{
2021-12-04 19:40:47 +00:00
body::{BoxBody, EitherBody, MessageBody},
header::HeaderMap,
BoxedPayloadStream, Extensions, HttpMessage, Method, Payload, RequestHead, Response,
ResponseHead, StatusCode, Uri, Version,
2019-03-02 06:51:32 +00:00
};
2021-08-06 21:42:31 +00:00
use actix_router::{IntoPatterns, Path, Patterns, Resource, ResourceDef, Url};
2021-12-04 19:40:47 +00:00
use actix_service::{
boxed::{BoxService, BoxServiceFactory},
IntoServiceFactory, ServiceFactory,
};
#[cfg(feature = "cookies")]
use cookie::{Cookie, ParseError as CookieParseError};
2019-03-02 06:51:32 +00:00
use crate::{
config::{AppConfig, AppService},
2021-08-06 21:42:31 +00:00
dev::ensure_leading_slash,
2021-12-28 02:37:13 +00:00
guard::{Guard, GuardContext},
2021-06-17 16:57:58 +00:00
info::ConnectionInfo,
rmap::ResourceMap,
Error, FromRequest, HttpRequest, HttpResponse,
};
2019-03-02 06:51:32 +00:00
2021-12-04 19:40:47 +00:00
pub(crate) type BoxedHttpService = BoxService<ServiceRequest, ServiceResponse<BoxBody>, Error>;
pub(crate) type BoxedHttpServiceFactory =
BoxServiceFactory<(), ServiceRequest, ServiceResponse<BoxBody>, Error, ()>;
pub trait HttpServiceFactory {
2019-04-15 14:32:49 +00:00
fn register(self, config: &mut AppService);
}
impl<T: HttpServiceFactory> HttpServiceFactory for Vec<T> {
fn register(self, config: &mut AppService) {
self.into_iter()
.for_each(|factory| factory.register(config));
}
}
2019-11-20 17:33:22 +00:00
pub(crate) trait AppServiceFactory {
2019-04-15 14:32:49 +00:00
fn register(&mut self, config: &mut AppService);
}
pub(crate) struct ServiceFactoryWrapper<T> {
factory: Option<T>,
}
impl<T> ServiceFactoryWrapper<T> {
pub fn new(factory: T) -> Self {
Self {
factory: Some(factory),
}
}
}
2019-11-20 17:33:22 +00:00
impl<T> AppServiceFactory for ServiceFactoryWrapper<T>
where
T: HttpServiceFactory,
{
2019-04-15 14:32:49 +00:00
fn register(&mut self, config: &mut AppService) {
if let Some(item) = self.factory.take() {
item.register(config)
}
}
}
2021-07-12 15:55:41 +00:00
/// A service level request wrapper.
2019-05-22 18:49:27 +00:00
///
2021-07-12 15:55:41 +00:00
/// Allows mutable access to request's internal structures.
2021-01-11 01:29:16 +00:00
pub struct ServiceRequest {
req: HttpRequest,
payload: Payload,
}
2019-03-02 06:51:32 +00:00
impl ServiceRequest {
2022-03-07 16:48:04 +00:00
/// Construct `ServiceRequest` from parts.
2021-01-11 01:29:16 +00:00
pub(crate) fn new(req: HttpRequest, payload: Payload) -> Self {
Self { req, payload }
2019-03-26 22:14:32 +00:00
}
2022-03-07 16:48:04 +00:00
/// Deconstruct `ServiceRequest` into inner parts.
2021-01-11 01:29:16 +00:00
#[inline]
pub fn into_parts(self) -> (HttpRequest, Payload) {
(self.req, self.payload)
2019-03-02 06:51:32 +00:00
}
2022-03-07 16:48:04 +00:00
/// Returns mutable accessors to inner parts.
2021-06-22 23:42:00 +00:00
#[inline]
pub fn parts_mut(&mut self) -> (&mut HttpRequest, &mut Payload) {
(&mut self.req, &mut self.payload)
}
/// Returns immutable accessors to inner parts.
#[inline]
pub fn parts(&self) -> (&HttpRequest, &Payload) {
(&self.req, &self.payload)
}
/// Returns immutable accessor to inner [`HttpRequest`].
#[inline]
pub fn request(&self) -> &HttpRequest {
&self.req
}
/// Derives a type from this request using an [extractor](crate::FromRequest).
///
/// Returns the `T` extractor's `Future` type which can be `await`ed. This is particularly handy
/// when you want to use an extractor in a middleware implementation.
///
/// # Examples
/// ```
/// use actix_web::{
/// dev::{ServiceRequest, ServiceResponse},
/// web::Path, Error
/// };
///
/// async fn my_helper(mut srv_req: ServiceRequest) -> Result<ServiceResponse, Error> {
/// let path = srv_req.extract::<Path<(String, u32)>>().await?;
/// // [...]
/// # todo!()
/// }
/// ```
pub fn extract<T>(&mut self) -> <T as FromRequest>::Future
where
T: FromRequest,
{
T::from_request(&self.req, &mut self.payload)
}
/// Construct request from parts.
2021-01-11 01:29:16 +00:00
pub fn from_parts(req: HttpRequest, payload: Payload) -> Self {
#[cfg(debug_assertions)]
if Rc::strong_count(&req.inner) > 1 {
log::warn!("Cloning an `HttpRequest` might cause panics.");
}
2021-01-11 01:29:16 +00:00
Self { req, payload }
}
2022-03-07 16:48:04 +00:00
/// Construct `ServiceRequest` with no payload from given `HttpRequest`.
#[inline]
2021-01-11 01:29:16 +00:00
pub fn from_request(req: HttpRequest) -> Self {
ServiceRequest {
req,
payload: Payload::None,
}
}
2022-03-07 16:48:04 +00:00
/// Create `ServiceResponse` from this request and given response.
2019-03-02 06:51:32 +00:00
#[inline]
pub fn into_response<B, R: Into<Response<B>>>(self, res: R) -> ServiceResponse<B> {
let res = HttpResponse::from(res.into());
ServiceResponse::new(self.req, res)
2019-03-02 06:51:32 +00:00
}
2022-03-07 16:48:04 +00:00
/// Create `ServiceResponse` from this request and given error.
2019-03-02 06:51:32 +00:00
#[inline]
pub fn error_response<E: Into<Error>>(self, err: E) -> ServiceResponse {
let res = HttpResponse::from_error(err.into());
ServiceResponse::new(self.req, res)
2019-03-02 06:51:32 +00:00
}
2022-03-07 16:48:04 +00:00
/// Returns a reference to the request head.
#[inline]
pub fn head(&self) -> &RequestHead {
2021-08-13 17:49:58 +00:00
self.req.head()
}
2022-03-07 16:48:04 +00:00
/// Returns a mutable reference to the request head.
#[inline]
pub fn head_mut(&mut self) -> &mut RequestHead {
2021-01-11 01:29:16 +00:00
self.req.head_mut()
}
2022-03-07 16:48:04 +00:00
/// Returns the request URI.
#[inline]
pub fn uri(&self) -> &Uri {
&self.head().uri
}
2022-03-07 16:48:04 +00:00
/// Returns the request method.
#[inline]
pub fn method(&self) -> &Method {
&self.head().method
}
2022-03-07 16:48:04 +00:00
/// Returns the request version.
#[inline]
pub fn version(&self) -> Version {
self.head().version
}
2022-03-07 16:48:04 +00:00
/// Returns a reference to request headers.
2019-03-06 03:10:45 +00:00
#[inline]
2019-04-02 20:35:01 +00:00
pub fn headers(&self) -> &HeaderMap {
&self.head().headers
}
2022-03-07 16:48:04 +00:00
/// Returns a mutable reference to request headers.
2019-04-02 20:35:01 +00:00
#[inline]
2019-03-06 03:10:45 +00:00
pub fn headers_mut(&mut self) -> &mut HeaderMap {
&mut self.head_mut().headers
}
2022-03-07 16:48:04 +00:00
/// Returns request path.
#[inline]
pub fn path(&self) -> &str {
self.head().uri.path()
}
2021-12-28 02:37:13 +00:00
/// Counterpart to [`HttpRequest::query_string`].
#[inline]
pub fn query_string(&self) -> &str {
self.req.query_string()
}
2022-03-07 16:48:04 +00:00
/// Returns peer's socket address.
2019-04-16 17:11:38 +00:00
///
/// See [`HttpRequest::peer_addr`] for more details.
2019-04-16 17:11:38 +00:00
///
/// [`HttpRequest::peer_addr`]: crate::HttpRequest::peer_addr
2019-04-16 17:11:38 +00:00
#[inline]
pub fn peer_addr(&self) -> Option<net::SocketAddr> {
self.head().peer_addr
}
2022-03-07 16:48:04 +00:00
/// Returns a reference to connection info.
2019-04-16 17:11:38 +00:00
#[inline]
2019-12-07 18:46:51 +00:00
pub fn connection_info(&self) -> Ref<'_, ConnectionInfo> {
2021-12-08 22:58:50 +00:00
self.req.connection_info()
2019-04-16 17:11:38 +00:00
}
2023-02-22 23:06:18 +00:00
/// Counterpart to [`HttpRequest::match_info`].
#[inline]
pub fn match_info(&self) -> &Path<Url> {
2021-01-11 01:29:16 +00:00
self.req.match_info()
}
2022-03-07 16:48:04 +00:00
/// Returns a mutable reference to the path match information.
2022-01-19 20:26:33 +00:00
#[inline]
pub fn match_info_mut(&mut self) -> &mut Path<Url> {
self.req.match_info_mut()
}
2021-12-28 02:37:13 +00:00
/// Counterpart to [`HttpRequest::match_name`].
#[inline]
pub fn match_name(&self) -> Option<&str> {
2021-01-11 01:29:16 +00:00
self.req.match_name()
}
2021-12-28 02:37:13 +00:00
/// Counterpart to [`HttpRequest::match_pattern`].
#[inline]
pub fn match_pattern(&self) -> Option<String> {
2021-01-11 01:29:16 +00:00
self.req.match_pattern()
}
2022-03-07 16:48:04 +00:00
/// Returns a reference to the application's resource map.
2023-02-22 23:06:18 +00:00
/// Counterpart to [`HttpRequest::resource_map`].
2021-08-06 21:42:31 +00:00
#[inline]
pub fn resource_map(&self) -> &ResourceMap {
2021-01-11 01:29:16 +00:00
self.req.resource_map()
}
2023-02-22 23:06:18 +00:00
/// Counterpart to [`HttpRequest::app_config`].
#[inline]
pub fn app_config(&self) -> &AppConfig {
2021-01-11 01:29:16 +00:00
self.req.app_config()
}
2019-04-03 22:25:52 +00:00
2021-12-28 02:37:13 +00:00
/// Counterpart to [`HttpRequest::app_data`].
#[inline]
pub fn app_data<T: 'static>(&self) -> Option<&T> {
2021-01-11 01:29:16 +00:00
for container in self.req.inner.app_data.iter().rev() {
if let Some(data) = container.get::<T>() {
return Some(data);
}
2019-04-03 22:25:52 +00:00
}
None
2019-04-03 22:25:52 +00:00
}
2021-12-28 02:37:13 +00:00
/// Counterpart to [`HttpRequest::conn_data`].
#[inline]
pub fn conn_data<T: 'static>(&self) -> Option<&T> {
self.req.conn_data()
}
2022-03-07 16:48:04 +00:00
/// Return request cookies.
#[cfg(feature = "cookies")]
2021-12-28 02:37:13 +00:00
#[inline]
pub fn cookies(&self) -> Result<Ref<'_, Vec<Cookie<'static>>>, CookieParseError> {
self.req.cookies()
}
/// Return request cookie.
#[cfg(feature = "cookies")]
2021-12-28 02:37:13 +00:00
#[inline]
pub fn cookie(&self, name: &str) -> Option<Cookie<'static>> {
self.req.cookie(name)
}
/// Set request payload.
#[inline]
pub fn set_payload(&mut self, payload: Payload) {
2021-01-11 01:29:16 +00:00
self.payload = payload;
}
/// Add data container to request's resolution set.
///
/// In middleware, prefer [`extensions_mut`](ServiceRequest::extensions_mut) for request-local
/// data since it is assumed that the same app data is presented for every request.
pub fn add_data_container(&mut self, extensions: Rc<Extensions>) {
2021-01-11 01:29:16 +00:00
Rc::get_mut(&mut (self.req).inner)
.unwrap()
.app_data
.push(extensions);
}
2021-12-28 02:37:13 +00:00
2022-10-14 11:20:38 +00:00
/// Creates a context object for use with a routing [guard](crate::guard).
2021-12-28 02:37:13 +00:00
#[inline]
pub fn guard_ctx(&self) -> GuardContext<'_> {
GuardContext { req: self }
}
2019-03-02 06:51:32 +00:00
}
impl Resource for ServiceRequest {
type Path = Url;
#[inline]
fn resource_path(&mut self) -> &mut Path<Self::Path> {
2019-03-04 19:47:53 +00:00
self.match_info_mut()
}
}
impl HttpMessage for ServiceRequest {
type Stream = BoxedPayloadStream;
2019-03-02 06:51:32 +00:00
#[inline]
fn headers(&self) -> &HeaderMap {
2019-03-06 02:47:18 +00:00
&self.head().headers
}
#[inline]
2019-12-07 18:46:51 +00:00
fn extensions(&self) -> Ref<'_, Extensions> {
2021-01-11 01:29:16 +00:00
self.req.extensions()
2019-03-06 02:47:18 +00:00
}
#[inline]
2019-12-07 18:46:51 +00:00
fn extensions_mut(&self) -> RefMut<'_, Extensions> {
2021-01-11 01:29:16 +00:00
self.req.extensions_mut()
2019-03-02 06:51:32 +00:00
}
#[inline]
fn take_payload(&mut self) -> Payload<Self::Stream> {
2021-01-11 01:29:16 +00:00
self.payload.take()
2019-03-02 06:51:32 +00:00
}
}
impl fmt::Debug for ServiceRequest {
2019-12-07 18:46:51 +00:00
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
writeln!(
f,
"\nServiceRequest {:?} {}:{}",
self.head().version,
self.head().method,
self.path()
)?;
if !self.query_string().is_empty() {
writeln!(f, " query: ?{:?}", self.query_string())?;
}
if !self.match_info().is_empty() {
writeln!(f, " params: {:?}", self.match_info())?;
}
writeln!(f, " headers:")?;
for (key, val) in self.headers().iter() {
writeln!(f, " {:?}: {:?}", key, val)?;
}
Ok(())
}
}
2021-07-12 15:55:41 +00:00
/// A service level response wrapper.
2021-12-04 19:40:47 +00:00
pub struct ServiceResponse<B = BoxBody> {
2019-03-02 06:51:32 +00:00
request: HttpRequest,
response: HttpResponse<B>,
2019-03-02 06:51:32 +00:00
}
2021-12-04 19:40:47 +00:00
impl ServiceResponse<BoxBody> {
/// Create service response from the error
pub fn from_err<E: Into<Error>>(err: E, request: HttpRequest) -> Self {
2021-06-17 16:57:58 +00:00
let response = HttpResponse::from_error(err);
2019-03-02 06:51:32 +00:00
ServiceResponse { request, response }
}
}
2019-03-02 06:51:32 +00:00
impl<B> ServiceResponse<B> {
/// Create service response instance
pub fn new(request: HttpRequest, response: HttpResponse<B>) -> Self {
ServiceResponse { request, response }
}
2019-03-10 04:40:09 +00:00
/// Create service response for error
#[inline]
pub fn error_response<E: Into<Error>>(self, err: E) -> ServiceResponse {
ServiceResponse::from_err(err, self.request)
2019-03-10 04:40:09 +00:00
}
/// Create service response
#[inline]
pub fn into_response<B1>(self, response: HttpResponse<B1>) -> ServiceResponse<B1> {
ServiceResponse::new(self.request, response)
}
/// Returns reference to original request.
2019-03-02 06:51:32 +00:00
#[inline]
pub fn request(&self) -> &HttpRequest {
&self.request
}
/// Returns reference to response.
2019-03-02 06:51:32 +00:00
#[inline]
pub fn response(&self) -> &HttpResponse<B> {
2019-03-02 06:51:32 +00:00
&self.response
}
/// Returns mutable reference to response.
2019-03-02 06:51:32 +00:00
#[inline]
pub fn response_mut(&mut self) -> &mut HttpResponse<B> {
2019-03-02 06:51:32 +00:00
&mut self.response
}
/// Returns response status code.
2019-04-02 20:35:01 +00:00
#[inline]
pub fn status(&self) -> StatusCode {
self.response.status()
}
/// Returns response's headers.
#[inline]
2019-04-02 20:35:01 +00:00
pub fn headers(&self) -> &HeaderMap {
self.response.headers()
}
/// Returns mutable response's headers.
#[inline]
2019-04-02 20:35:01 +00:00
pub fn headers_mut(&mut self) -> &mut HeaderMap {
self.response.headers_mut()
}
/// Destructures `ServiceResponse` into request and response components.
#[inline]
pub fn into_parts(self) -> (HttpRequest, HttpResponse<B>) {
(self.request, self.response)
}
/// Map the current body type to another using a closure. Returns a new response.
///
/// Closure receives the response head and the current body type.
2021-12-04 19:40:47 +00:00
#[inline]
2019-03-06 02:47:18 +00:00
pub fn map_body<F, B2>(self, f: F) -> ServiceResponse<B2>
2019-03-02 06:51:32 +00:00
where
F: FnOnce(&mut ResponseHead, B) -> B2,
2019-03-02 06:51:32 +00:00
{
let response = self.response.map_body(f);
ServiceResponse {
response,
request: self.request,
}
}
2021-12-04 19:40:47 +00:00
#[inline]
pub fn map_into_left_body<R>(self) -> ServiceResponse<EitherBody<B, R>> {
self.map_body(|_, body| EitherBody::left(body))
}
#[inline]
pub fn map_into_right_body<L>(self) -> ServiceResponse<EitherBody<L, B>> {
self.map_body(|_, body| EitherBody::right(body))
}
#[inline]
pub fn map_into_boxed_body(self) -> ServiceResponse<BoxBody>
where
B: MessageBody + 'static,
{
self.map_body(|_, body| body.boxed())
2021-12-04 19:40:47 +00:00
}
/// Consumes the response and returns its body.
#[inline]
pub fn into_body(self) -> B {
self.response.into_body()
}
2019-03-02 06:51:32 +00:00
}
impl<B> From<ServiceResponse<B>> for HttpResponse<B> {
fn from(res: ServiceResponse<B>) -> HttpResponse<B> {
res.response
}
}
2021-01-07 01:13:46 +00:00
impl<B> From<ServiceResponse<B>> for Response<B> {
2021-01-07 02:41:05 +00:00
fn from(res: ServiceResponse<B>) -> Response<B> {
res.response.into()
2019-03-02 06:51:32 +00:00
}
}
impl<B> fmt::Debug for ServiceResponse<B>
where
B: MessageBody,
B::Error: Into<Error>,
{
2019-12-07 18:46:51 +00:00
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let res = writeln!(
f,
"\nServiceResponse {:?} {}{}",
self.response.head().version,
self.response.head().status,
self.response.head().reason.unwrap_or(""),
);
let _ = writeln!(f, " headers:");
for (key, val) in self.response.head().headers.iter() {
let _ = writeln!(f, " {:?}: {:?}", key, val);
}
let _ = writeln!(f, " body: {:?}", self.response.body().size());
res
}
}
2019-04-01 03:43:00 +00:00
2019-04-24 22:29:15 +00:00
pub struct WebService {
2021-08-06 21:42:31 +00:00
rdef: Patterns,
2019-04-24 22:29:15 +00:00
name: Option<String>,
2019-07-17 09:48:37 +00:00
guards: Vec<Box<dyn Guard>>,
2019-04-24 22:29:15 +00:00
}
impl WebService {
/// Create new `WebService` instance.
2021-08-06 21:42:31 +00:00
pub fn new<T: IntoPatterns>(path: T) -> Self {
2019-04-24 22:29:15 +00:00
WebService {
rdef: path.patterns(),
2019-04-24 22:29:15 +00:00
name: None,
guards: Vec::new(),
}
}
/// Set service name.
///
2021-09-03 17:00:43 +00:00
/// Name is used for URL generation.
2019-04-24 22:29:15 +00:00
pub fn name(mut self, name: &str) -> Self {
self.name = Some(name.to_string());
self
}
/// Add match guard to a web service.
///
/// ```
2019-11-20 17:33:22 +00:00
/// use actix_web::{web, guard, dev, App, Error, HttpResponse};
2019-04-24 22:29:15 +00:00
///
2019-11-21 09:56:49 +00:00
/// async fn index(req: dev::ServiceRequest) -> Result<dev::ServiceResponse, Error> {
/// Ok(req.into_response(HttpResponse::Ok().finish()))
2019-04-24 22:29:15 +00:00
/// }
///
/// let app = App::new()
/// .service(
/// web::service("/app")
/// .guard(guard::Header("content-type", "text/plain"))
/// .finish(index)
/// );
2019-04-24 22:29:15 +00:00
/// ```
pub fn guard<G: Guard + 'static>(mut self, guard: G) -> Self {
self.guards.push(Box::new(guard));
self
}
/// Set a service factory implementation and generate web service.
pub fn finish<T, F>(self, service: F) -> impl HttpServiceFactory
where
F: IntoServiceFactory<T, ServiceRequest>,
2019-11-20 17:33:22 +00:00
T: ServiceFactory<
ServiceRequest,
2019-05-12 15:34:51 +00:00
Config = (),
2019-04-24 22:29:15 +00:00
Response = ServiceResponse,
Error = Error,
InitError = (),
> + 'static,
{
WebServiceImpl {
2019-11-20 17:33:22 +00:00
srv: service.into_factory(),
2019-04-24 22:29:15 +00:00
rdef: self.rdef,
name: self.name,
guards: self.guards,
}
}
}
struct WebServiceImpl<T> {
srv: T,
2021-08-06 21:42:31 +00:00
rdef: Patterns,
2019-04-24 22:29:15 +00:00
name: Option<String>,
2019-07-17 09:48:37 +00:00
guards: Vec<Box<dyn Guard>>,
2019-04-24 22:29:15 +00:00
}
impl<T> HttpServiceFactory for WebServiceImpl<T>
where
2019-11-20 17:33:22 +00:00
T: ServiceFactory<
ServiceRequest,
2019-05-12 15:34:51 +00:00
Config = (),
2019-04-24 22:29:15 +00:00
Response = ServiceResponse,
Error = Error,
InitError = (),
> + 'static,
{
fn register(mut self, config: &mut AppService) {
let guards = if self.guards.is_empty() {
None
} else {
2020-05-17 01:54:42 +00:00
Some(std::mem::take(&mut self.guards))
2019-04-24 22:29:15 +00:00
};
let mut rdef = if config.is_root() || !self.rdef.is_empty() {
2021-08-06 21:42:31 +00:00
ResourceDef::new(ensure_leading_slash(self.rdef))
2019-04-24 22:29:15 +00:00
} else {
ResourceDef::new(self.rdef)
2019-04-24 22:29:15 +00:00
};
2021-08-06 21:42:31 +00:00
2019-04-24 22:29:15 +00:00
if let Some(ref name) = self.name {
2021-08-06 21:42:31 +00:00
rdef.set_name(name);
2019-04-24 22:29:15 +00:00
}
2021-08-06 21:42:31 +00:00
2019-04-24 22:29:15 +00:00
config.register_service(rdef, guards, self.srv, None)
}
}
/// Macro to help register different types of services at the same time.
///
/// The max number of services that can be grouped together is 12 and all must implement the
/// [`HttpServiceFactory`] trait.
///
/// # Examples
/// ```
/// use actix_web::{services, web, App};
///
/// let services = services![
/// web::resource("/test2").to(|| async { "test2" }),
/// web::scope("/test3").route("/", web::get().to(|| async { "test3" }))
/// ];
///
/// let app = App::new().service(services);
///
/// // services macro just convert multiple services to a tuple.
/// // below would also work without importing the macro.
/// let app = App::new().service((
/// web::resource("/test2").to(|| async { "test2" }),
/// web::scope("/test3").route("/", web::get().to(|| async { "test3" }))
/// ));
/// ```
#[macro_export]
macro_rules! services {
($($x:expr),+ $(,)?) => {
($($x,)+)
}
}
/// HttpServiceFactory trait impl for tuples
2021-03-23 13:42:46 +00:00
macro_rules! service_tuple ({ $($T:ident)+ } => {
impl<$($T: HttpServiceFactory),+> HttpServiceFactory for ($($T,)+) {
2021-03-23 13:42:46 +00:00
#[allow(non_snake_case)]
fn register(self, config: &mut AppService) {
2021-03-23 13:42:46 +00:00
let ($($T,)*) = self;
$($T.register(config);)+
}
}
});
2021-03-23 13:42:46 +00:00
service_tuple! { A }
service_tuple! { A B }
service_tuple! { A B C }
service_tuple! { A B C D }
service_tuple! { A B C D E }
service_tuple! { A B C D E F }
service_tuple! { A B C D E F G }
service_tuple! { A B C D E F G H }
service_tuple! { A B C D E F G H I }
service_tuple! { A B C D E F G H I J }
service_tuple! { A B C D E F G H I J K }
service_tuple! { A B C D E F G H I J K L }
2019-04-01 03:43:00 +00:00
#[cfg(test)]
mod tests {
2019-11-20 17:33:22 +00:00
use actix_service::Service;
2021-04-01 14:26:13 +00:00
use actix_utils::future::ok;
2019-04-24 22:29:15 +00:00
2023-07-17 01:38:12 +00:00
use super::*;
use crate::{
guard, http,
test::{self, init_service, TestRequest},
web, App,
2023-07-17 01:38:12 +00:00
};
2019-11-26 05:25:50 +00:00
#[actix_rt::test]
async fn test_service() {
2023-07-17 01:38:12 +00:00
let srv =
init_service(
App::new().service(web::service("/test").name("test").finish(
|req: ServiceRequest| ok(req.into_response(HttpResponse::Ok().finish())),
)),
)
.await;
2019-11-26 05:25:50 +00:00
let req = TestRequest::with_uri("/test").to_request();
let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), http::StatusCode::OK);
2023-07-17 01:38:12 +00:00
let srv =
init_service(
App::new().service(web::service("/test").guard(guard::Get()).finish(
|req: ServiceRequest| ok(req.into_response(HttpResponse::Ok().finish())),
)),
)
.await;
2019-11-26 05:25:50 +00:00
let req = TestRequest::with_uri("/test")
.method(http::Method::PUT)
.to_request();
let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), http::StatusCode::NOT_FOUND);
2019-04-24 22:29:15 +00:00
}
// allow deprecated App::data
#[allow(deprecated)]
#[actix_rt::test]
async fn test_service_data() {
2023-07-17 01:38:12 +00:00
let srv = init_service(
App::new()
.data(42u32)
.service(
web::service("/test")
.name("test")
.finish(|req: ServiceRequest| {
2021-02-11 23:03:17 +00:00
assert_eq!(req.app_data::<web::Data<u32>>().unwrap().as_ref(), &42);
ok(req.into_response(HttpResponse::Ok().finish()))
2023-07-17 01:38:12 +00:00
}),
),
)
.await;
let req = TestRequest::with_uri("/test").to_request();
let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), http::StatusCode::OK);
}
2019-04-01 03:43:00 +00:00
#[test]
fn test_fmt_debug() {
let req = TestRequest::get()
.uri("/index.html?test=1")
2021-01-15 02:11:10 +00:00
.insert_header(("x-test", "111"))
2019-04-01 03:43:00 +00:00
.to_srv_request();
let s = format!("{:?}", req);
assert!(s.contains("ServiceRequest"));
assert!(s.contains("test=1"));
assert!(s.contains("x-test"));
2021-01-15 02:11:10 +00:00
let res = HttpResponse::Ok().insert_header(("x-test", "111")).finish();
2019-04-01 03:43:00 +00:00
let res = TestRequest::post()
.uri("/index.html?test=1")
.to_srv_response(res);
let s = format!("{:?}", res);
assert!(s.contains("ServiceResponse"));
assert!(s.contains("x-test"));
}
#[actix_rt::test]
async fn test_services_macro() {
let scoped = services![
web::service("/scoped_test1").name("scoped_test1").finish(
2023-07-17 01:38:12 +00:00
|req: ServiceRequest| async { Ok(req.into_response(HttpResponse::Ok().finish())) }
),
web::resource("/scoped_test2").to(|| async { "test2" }),
];
let services = services![
web::service("/test1")
.name("test")
.finish(|req: ServiceRequest| async {
Ok(req.into_response(HttpResponse::Ok().finish()))
}),
web::resource("/test2").to(|| async { "test2" }),
web::scope("/test3").service(scoped)
];
let srv = init_service(App::new().service(services)).await;
let req = TestRequest::with_uri("/test1").to_request();
let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), http::StatusCode::OK);
let req = TestRequest::with_uri("/test2").to_request();
let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), http::StatusCode::OK);
let req = TestRequest::with_uri("/test3/scoped_test1").to_request();
let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), http::StatusCode::OK);
let req = TestRequest::with_uri("/test3/scoped_test2").to_request();
let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), http::StatusCode::OK);
}
#[actix_rt::test]
async fn test_services_vec() {
let services = vec![
web::resource("/test1").to(|| async { "test1" }),
web::resource("/test2").to(|| async { "test2" }),
];
let scoped = vec![
web::resource("/scoped_test1").to(|| async { "test1" }),
web::resource("/scoped_test2").to(|| async { "test2" }),
];
let srv = init_service(
App::new()
.service(services)
.service(web::scope("/test3").service(scoped)),
)
.await;
let req = TestRequest::with_uri("/test1").to_request();
let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), http::StatusCode::OK);
let req = TestRequest::with_uri("/test2").to_request();
let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), http::StatusCode::OK);
let req = TestRequest::with_uri("/test3/scoped_test1").to_request();
let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), http::StatusCode::OK);
let req = TestRequest::with_uri("/test3/scoped_test2").to_request();
let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), http::StatusCode::OK);
}
#[actix_rt::test]
#[should_panic(expected = "called `Option::unwrap()` on a `None` value")]
async fn cloning_request_panics() {
async fn index(_name: web::Path<(String,)>) -> &'static str {
""
}
let app = test::init_service(
App::new()
.wrap_fn(|req, svc| {
let (req, pl) = req.into_parts();
let _req2 = req.clone();
let req = ServiceRequest::from_parts(req, pl);
svc.call(req)
})
.route("/", web::get().to(|| async { "" }))
2023-07-17 01:38:12 +00:00
.service(web::resource("/resource1/{name}/index.html").route(web::get().to(index))),
)
.await;
let req = test::TestRequest::default().to_request();
let _res = test::call_service(&app, req).await;
}
2019-04-01 03:43:00 +00:00
}