1
0
mirror of https://github.com/fafhrd91/actix-web synced 2024-11-30 18:44:35 +01:00
actix-web/src/service.rs

639 lines
18 KiB
Rust
Raw Normal View History

use std::cell::{Ref, RefMut};
use std::rc::Rc;
2019-04-16 19:11:38 +02:00
use std::{fmt, net};
2019-03-02 07:51:32 +01:00
use actix_http::body::{Body, MessageBody, ResponseBody};
2019-04-02 22:35:01 +02:00
use actix_http::http::{HeaderMap, Method, StatusCode, Uri, Version};
2019-03-02 07:51:32 +01:00
use actix_http::{
Error, Extensions, HttpMessage, Payload, PayloadStream, RequestHead, Response,
ResponseHead,
2019-03-02 07:51:32 +01:00
};
use actix_router::{IntoPattern, Path, Resource, ResourceDef, Url};
2019-11-20 18:33:22 +01:00
use actix_service::{IntoServiceFactory, ServiceFactory};
2019-03-02 07:51:32 +01:00
2019-04-15 16:32:49 +02:00
use crate::config::{AppConfig, AppService};
2019-04-25 00:29:15 +02:00
use crate::dev::insert_slash;
use crate::guard::Guard;
2019-04-16 19:11:38 +02:00
use crate::info::ConnectionInfo;
2019-03-02 07:51:32 +01:00
use crate::request::HttpRequest;
use crate::rmap::ResourceMap;
2019-03-02 07:51:32 +01:00
pub trait HttpServiceFactory {
2019-04-15 16:32:49 +02:00
fn register(self, config: &mut AppService);
}
2019-11-20 18:33:22 +01:00
pub(crate) trait AppServiceFactory {
2019-04-15 16:32:49 +02: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 18:33:22 +01:00
impl<T> AppServiceFactory for ServiceFactoryWrapper<T>
where
T: HttpServiceFactory,
{
2019-04-15 16:32:49 +02:00
fn register(&mut self, config: &mut AppService) {
if let Some(item) = self.factory.take() {
item.register(config)
}
}
}
2019-05-22 20:49:27 +02:00
/// An service http request
///
/// ServiceRequest allows mutable access to request's internal structures
pub struct ServiceRequest(HttpRequest);
2019-03-02 07:51:32 +01:00
impl ServiceRequest {
2019-05-22 20:49:27 +02:00
/// Construct service request
pub(crate) fn new(req: HttpRequest) -> Self {
ServiceRequest(req)
2019-03-26 23:14:32 +01:00
}
/// Deconstruct request into parts
2019-05-22 20:49:27 +02:00
pub fn into_parts(mut self) -> (HttpRequest, Payload) {
let pl = Rc::get_mut(&mut (self.0).0).unwrap().payload.take();
(self.0, pl)
2019-03-02 07:51:32 +01:00
}
/// Construct request from parts.
///
2020-04-21 05:09:35 +02:00
/// `ServiceRequest` can be re-constructed only if `req` hasn't been cloned.
pub fn from_parts(
mut req: HttpRequest,
pl: Payload,
) -> Result<Self, (HttpRequest, Payload)> {
if Rc::strong_count(&req.0) == 1 && Rc::weak_count(&req.0) == 0 {
Rc::get_mut(&mut req.0).unwrap().payload = pl;
Ok(ServiceRequest(req))
} else {
Err((req, pl))
}
}
/// Construct request from request.
///
/// `HttpRequest` implements `Clone` trait via `Rc` type. `ServiceRequest`
/// can be re-constructed only if rc's strong pointers count eq 1 and
/// weak pointers count is 0.
pub fn from_request(req: HttpRequest) -> Result<Self, HttpRequest> {
if Rc::strong_count(&req.0) == 1 && Rc::weak_count(&req.0) == 0 {
Ok(ServiceRequest(req))
} else {
Err(req)
}
}
2019-03-02 07:51:32 +01:00
/// Create service response
#[inline]
pub fn into_response<B, R: Into<Response<B>>>(self, res: R) -> ServiceResponse<B> {
2019-05-22 20:49:27 +02:00
ServiceResponse::new(self.0, res.into())
2019-03-02 07:51:32 +01:00
}
/// Create service response for error
#[inline]
2019-03-10 05:40:09 +01:00
pub fn error_response<B, E: Into<Error>>(self, err: E) -> ServiceResponse<B> {
let res: Response = err.into().into();
2019-05-22 20:49:27 +02:00
ServiceResponse::new(self.0, res.into_body())
2019-03-02 07:51:32 +01:00
}
/// This method returns reference to the request head
#[inline]
pub fn head(&self) -> &RequestHead {
2019-05-22 20:49:27 +02:00
&self.0.head()
}
/// This method returns reference to the request head
#[inline]
pub fn head_mut(&mut self) -> &mut RequestHead {
2019-05-22 20:49:27 +02:00
self.0.head_mut()
}
/// Request's uri.
#[inline]
pub fn uri(&self) -> &Uri {
&self.head().uri
}
/// Read the Request method.
#[inline]
pub fn method(&self) -> &Method {
&self.head().method
}
/// Read the Request Version.
#[inline]
pub fn version(&self) -> Version {
self.head().version
}
2019-03-06 04:10:45 +01:00
#[inline]
2019-04-02 22:35:01 +02:00
/// Returns request's headers.
pub fn headers(&self) -> &HeaderMap {
&self.head().headers
}
#[inline]
/// Returns mutable request's headers.
2019-03-06 04:10:45 +01:00
pub fn headers_mut(&mut self) -> &mut HeaderMap {
&mut self.head_mut().headers
}
/// The target path of this Request.
#[inline]
pub fn path(&self) -> &str {
self.head().uri.path()
}
/// The query string in the URL.
///
/// E.g., id=10
#[inline]
pub fn query_string(&self) -> &str {
if let Some(query) = self.uri().query().as_ref() {
query
} else {
""
}
}
2019-04-16 19:11:38 +02:00
/// Peer socket address
///
/// Peer address is actual socket address, if proxy is used in front of
/// actix http server, then peer address would be address of this proxy.
///
/// To get client connection information `ConnectionInfo` should be used.
#[inline]
pub fn peer_addr(&self) -> Option<net::SocketAddr> {
self.head().peer_addr
}
/// Get *ConnectionInfo* for the current request.
#[inline]
2019-12-07 19:46:51 +01:00
pub fn connection_info(&self) -> Ref<'_, ConnectionInfo> {
2019-04-16 19:11:38 +02:00
ConnectionInfo::get(self.head(), &*self.app_config())
}
/// Get a reference to the Path parameters.
///
/// Params is a container for url parameters.
/// A variable segment is specified in the form `{identifier}`,
/// where the identifier can be used later in a request handler to
/// access the matched value for that segment.
#[inline]
pub fn match_info(&self) -> &Path<Url> {
2019-05-22 20:49:27 +02:00
self.0.match_info()
}
/// Counterpart to [`HttpRequest::match_name`](super::HttpRequest::match_name()).
#[inline]
pub fn match_name(&self) -> Option<&str> {
self.0.match_name()
}
/// Counterpart to [`HttpRequest::match_pattern`](super::HttpRequest::match_pattern()).
#[inline]
pub fn match_pattern(&self) -> Option<String> {
self.0.match_pattern()
}
2019-03-02 07:51:32 +01:00
#[inline]
/// Get a mutable reference to the Path parameters.
2019-03-02 07:51:32 +01:00
pub fn match_info_mut(&mut self) -> &mut Path<Url> {
2019-05-22 20:49:27 +02:00
self.0.match_info_mut()
2019-03-02 07:51:32 +01:00
}
#[inline]
/// Get a reference to a `ResourceMap` of current application.
pub fn resource_map(&self) -> &ResourceMap {
self.0.resource_map()
}
/// Service configuration
#[inline]
pub fn app_config(&self) -> &AppConfig {
2019-05-22 20:49:27 +02:00
self.0.app_config()
}
2019-04-04 00:25:52 +02:00
/// Counterpart to [`HttpRequest::app_data`](super::HttpRequest::app_data()).
pub fn app_data<T: 'static>(&self) -> Option<&T> {
for container in (self.0).0.app_data.iter().rev() {
if let Some(data) = container.get::<T>() {
return Some(data);
}
2019-04-04 00:25:52 +02:00
}
None
2019-04-04 00:25:52 +02:00
}
/// Set request payload.
pub fn set_payload(&mut self, payload: Payload) {
Rc::get_mut(&mut (self.0).0).unwrap().payload = payload;
}
#[doc(hidden)]
/// Add app data container to request's resolution set.
pub fn add_data_container(&mut self, extensions: Rc<Extensions>) {
Rc::get_mut(&mut (self.0).0)
.unwrap()
.app_data
.push(extensions);
}
2019-03-02 07:51:32 +01:00
}
impl Resource<Url> for ServiceRequest {
2019-03-04 20:47:53 +01:00
fn resource_path(&mut self) -> &mut Path<Url> {
self.match_info_mut()
}
}
impl HttpMessage for ServiceRequest {
type Stream = PayloadStream;
2019-03-02 07:51:32 +01:00
#[inline]
2019-03-06 03:47:18 +01:00
/// Returns Request's headers.
2019-03-02 07:51:32 +01:00
fn headers(&self) -> &HeaderMap {
2019-03-06 03:47:18 +01:00
&self.head().headers
}
/// Request extensions
#[inline]
2019-12-07 19:46:51 +01:00
fn extensions(&self) -> Ref<'_, Extensions> {
2019-05-22 20:49:27 +02:00
self.0.extensions()
2019-03-06 03:47:18 +01:00
}
/// Mutable reference to a the request's extensions
#[inline]
2019-12-07 19:46:51 +01:00
fn extensions_mut(&self) -> RefMut<'_, Extensions> {
2019-05-22 20:49:27 +02:00
self.0.extensions_mut()
2019-03-02 07:51:32 +01:00
}
#[inline]
fn take_payload(&mut self) -> Payload<Self::Stream> {
2019-05-22 20:49:27 +02:00
Rc::get_mut(&mut (self.0).0).unwrap().payload.take()
2019-03-02 07:51:32 +01:00
}
}
impl fmt::Debug for ServiceRequest {
2019-12-07 19:46:51 +01: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(())
}
}
2019-03-02 07:51:32 +01:00
pub struct ServiceResponse<B = Body> {
request: HttpRequest,
response: Response<B>,
}
impl<B> ServiceResponse<B> {
/// Create service response instance
pub fn new(request: HttpRequest, response: Response<B>) -> Self {
ServiceResponse { request, response }
}
/// Create service response from the error
pub fn from_err<E: Into<Error>>(err: E, request: HttpRequest) -> Self {
let e: Error = err.into();
let res: Response = e.into();
ServiceResponse {
request,
response: res.into_body(),
}
}
2019-03-10 05:40:09 +01:00
/// Create service response for error
#[inline]
pub fn error_response<E: Into<Error>>(self, err: E) -> Self {
Self::from_err(err, self.request)
}
/// Create service response
#[inline]
pub fn into_response<B1>(self, response: Response<B1>) -> ServiceResponse<B1> {
ServiceResponse::new(self.request, response)
}
2019-03-02 07:51:32 +01:00
/// Get reference to original request
#[inline]
pub fn request(&self) -> &HttpRequest {
&self.request
}
/// Get reference to response
#[inline]
pub fn response(&self) -> &Response<B> {
&self.response
}
/// Get mutable reference to response
#[inline]
pub fn response_mut(&mut self) -> &mut Response<B> {
&mut self.response
}
2019-04-02 22:35:01 +02:00
/// Get the response status code
#[inline]
pub fn status(&self) -> StatusCode {
self.response.status()
}
#[inline]
/// Returns response's headers.
pub fn headers(&self) -> &HeaderMap {
self.response.headers()
}
#[inline]
/// Returns mutable response's headers.
pub fn headers_mut(&mut self) -> &mut HeaderMap {
self.response.headers_mut()
}
2019-03-06 03:47:18 +01:00
/// Execute closure and in case of error convert it to response.
pub fn checked_expr<F, E>(mut self, f: F) -> Self
where
F: FnOnce(&mut Self) -> Result<(), E>,
E: Into<Error>,
{
match f(&mut self) {
Ok(_) => self,
Err(err) => {
let res: Response = err.into().into();
ServiceResponse::new(self.request, res.into_body())
}
}
}
/// Extract response body
pub fn take_body(&mut self) -> ResponseBody<B> {
self.response.take_body()
}
2019-03-02 07:51:32 +01:00
}
2019-03-06 03:47:18 +01:00
impl<B> ServiceResponse<B> {
2019-03-02 07:51:32 +01:00
/// Set a new body
2019-03-06 03:47:18 +01:00
pub fn map_body<F, B2>(self, f: F) -> ServiceResponse<B2>
2019-03-02 07:51:32 +01:00
where
F: FnOnce(&mut ResponseHead, ResponseBody<B>) -> ResponseBody<B2>,
{
let response = self.response.map_body(f);
ServiceResponse {
response,
request: self.request,
}
}
}
2019-03-06 03:47:18 +01:00
impl<B> Into<Response<B>> for ServiceResponse<B> {
2019-03-02 07:51:32 +01:00
fn into(self) -> Response<B> {
self.response
}
}
impl<B: MessageBody> fmt::Debug for ServiceResponse<B> {
2019-12-07 19:46:51 +01: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 05:43:00 +02:00
2019-04-25 00:29:15 +02:00
pub struct WebService {
rdef: Vec<String>,
2019-04-25 00:29:15 +02:00
name: Option<String>,
2019-07-17 11:48:37 +02:00
guards: Vec<Box<dyn Guard>>,
2019-04-25 00:29:15 +02:00
}
impl WebService {
/// Create new `WebService` instance.
pub fn new<T: IntoPattern>(path: T) -> Self {
2019-04-25 00:29:15 +02:00
WebService {
rdef: path.patterns(),
2019-04-25 00:29:15 +02:00
name: None,
guards: Vec::new(),
}
}
/// Set service name.
///
/// Name is used for url generation.
pub fn name(mut self, name: &str) -> Self {
self.name = Some(name.to_string());
self
}
/// Add match guard to a web service.
///
/// ```rust
2019-11-20 18:33:22 +01:00
/// use actix_web::{web, guard, dev, App, Error, HttpResponse};
2019-04-25 00:29:15 +02:00
///
2019-11-21 10:56:49 +01:00
/// async fn index(req: dev::ServiceRequest) -> Result<dev::ServiceResponse, Error> {
/// Ok(req.into_response(HttpResponse::Ok().finish()))
2019-04-25 00:29:15 +02:00
/// }
///
/// fn main() {
/// let app = App::new()
/// .service(
/// web::service("/app")
/// .guard(guard::Header("content-type", "text/plain"))
/// .finish(index)
/// );
/// }
/// ```
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 18:33:22 +01:00
T: ServiceFactory<
ServiceRequest,
2019-05-12 17:34:51 +02:00
Config = (),
2019-04-25 00:29:15 +02:00
Response = ServiceResponse,
Error = Error,
InitError = (),
> + 'static,
{
WebServiceImpl {
2019-11-20 18:33:22 +01:00
srv: service.into_factory(),
2019-04-25 00:29:15 +02:00
rdef: self.rdef,
name: self.name,
guards: self.guards,
}
}
}
struct WebServiceImpl<T> {
srv: T,
rdef: Vec<String>,
2019-04-25 00:29:15 +02:00
name: Option<String>,
2019-07-17 11:48:37 +02:00
guards: Vec<Box<dyn Guard>>,
2019-04-25 00:29:15 +02:00
}
impl<T> HttpServiceFactory for WebServiceImpl<T>
where
2019-11-20 18:33:22 +01:00
T: ServiceFactory<
ServiceRequest,
2019-05-12 17:34:51 +02:00
Config = (),
2019-04-25 00:29:15 +02: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 03:54:42 +02:00
Some(std::mem::take(&mut self.guards))
2019-04-25 00:29:15 +02:00
};
let mut rdef = if config.is_root() || !self.rdef.is_empty() {
ResourceDef::new(insert_slash(self.rdef))
2019-04-25 00:29:15 +02:00
} else {
ResourceDef::new(self.rdef)
2019-04-25 00:29:15 +02:00
};
if let Some(ref name) = self.name {
*rdef.name_mut() = name.clone();
}
config.register_service(rdef, guards, self.srv, None)
}
}
2019-04-01 05:43:00 +02:00
#[cfg(test)]
mod tests {
2019-04-25 00:29:15 +02:00
use super::*;
2019-11-26 06:25:50 +01:00
use crate::test::{init_service, TestRequest};
2019-04-25 00:29:15 +02:00
use crate::{guard, http, web, App, HttpResponse};
2019-11-20 18:33:22 +01:00
use actix_service::Service;
2020-05-18 04:47:20 +02:00
use futures_util::future::ok;
2019-04-25 00:29:15 +02:00
#[test]
fn test_service_request() {
let req = TestRequest::default().to_srv_request();
let (r, pl) = req.into_parts();
assert!(ServiceRequest::from_parts(r, pl).is_ok());
let req = TestRequest::default().to_srv_request();
let (r, pl) = req.into_parts();
let _r2 = r.clone();
assert!(ServiceRequest::from_parts(r, pl).is_err());
let req = TestRequest::default().to_srv_request();
let (r, _pl) = req.into_parts();
assert!(ServiceRequest::from_request(r).is_ok());
let req = TestRequest::default().to_srv_request();
let (r, _pl) = req.into_parts();
let _r2 = r.clone();
assert!(ServiceRequest::from_request(r).is_err());
}
2019-11-26 06:25:50 +01:00
#[actix_rt::test]
async fn test_service() {
let mut srv = init_service(
App::new().service(web::service("/test").name("test").finish(
|req: ServiceRequest| ok(req.into_response(HttpResponse::Ok().finish())),
)),
)
.await;
let req = TestRequest::with_uri("/test").to_request();
let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), http::StatusCode::OK);
let mut srv = init_service(
App::new().service(web::service("/test").guard(guard::Get()).finish(
|req: ServiceRequest| ok(req.into_response(HttpResponse::Ok().finish())),
)),
)
.await;
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-25 00:29:15 +02:00
}
#[actix_rt::test]
async fn test_service_data() {
let mut srv = init_service(
App::new()
.data(42u32)
.service(web::service("/test").name("test").finish(
|req: ServiceRequest| {
assert_eq!(
req.app_data::<web::Data<u32>>().unwrap().as_ref(),
&42
);
ok(req.into_response(HttpResponse::Ok().finish()))
},
)),
)
.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 05:43:00 +02:00
#[test]
fn test_fmt_debug() {
let req = TestRequest::get()
.uri("/index.html?test=1")
.header("x-test", "111")
.to_srv_request();
let s = format!("{:?}", req);
assert!(s.contains("ServiceRequest"));
assert!(s.contains("test=1"));
assert!(s.contains("x-test"));
let res = HttpResponse::Ok().header("x-test", "111").finish();
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"));
}
}