1
0
mirror of https://github.com/fafhrd91/actix-web synced 2025-06-25 22:49:21 +02:00

remove Deref

This commit is contained in:
Nikolay Kim
2019-04-02 13:35:01 -07:00
parent e282ef7925
commit bca31eb7ad
22 changed files with 192 additions and 172 deletions

View File

@ -92,7 +92,7 @@ impl<T: 'static, P> FromRequest<P> for Data<T> {
#[inline]
fn from_request(req: &mut ServiceFromRequest<P>) -> Self::Future {
if let Some(st) = req.config().extensions().get::<Data<T>>() {
if let Some(st) = req.request().config().extensions().get::<Data<T>>() {
Ok(st.clone())
} else {
Err(ErrorInternalServerError(

View File

@ -73,6 +73,15 @@ where
}
}
impl<F> Guard for F
where
F: Fn(&RequestHead) -> bool,
{
fn check(&self, head: &RequestHead) -> bool {
(self)(head)
}
}
/// Return guard that matches if any of supplied guards.
///
/// ```rust
@ -300,13 +309,13 @@ mod tests {
.to_http_request();
let pred = Header("transfer-encoding", "chunked");
assert!(pred.check(&req));
assert!(pred.check(req.head()));
let pred = Header("transfer-encoding", "other");
assert!(!pred.check(&req));
assert!(!pred.check(req.head()));
let pred = Header("content-type", "other");
assert!(!pred.check(&req));
assert!(!pred.check(req.head()));
}
// #[test]
@ -332,50 +341,50 @@ mod tests {
.method(Method::POST)
.to_http_request();
assert!(Get().check(&req));
assert!(!Get().check(&req2));
assert!(Post().check(&req2));
assert!(!Post().check(&req));
assert!(Get().check(req.head()));
assert!(!Get().check(req2.head()));
assert!(Post().check(req2.head()));
assert!(!Post().check(req.head()));
let r = TestRequest::default().method(Method::PUT).to_http_request();
assert!(Put().check(&r));
assert!(!Put().check(&req));
assert!(Put().check(r.head()));
assert!(!Put().check(req.head()));
let r = TestRequest::default()
.method(Method::DELETE)
.to_http_request();
assert!(Delete().check(&r));
assert!(!Delete().check(&req));
assert!(Delete().check(r.head()));
assert!(!Delete().check(req.head()));
let r = TestRequest::default()
.method(Method::HEAD)
.to_http_request();
assert!(Head().check(&r));
assert!(!Head().check(&req));
assert!(Head().check(r.head()));
assert!(!Head().check(req.head()));
let r = TestRequest::default()
.method(Method::OPTIONS)
.to_http_request();
assert!(Options().check(&r));
assert!(!Options().check(&req));
assert!(Options().check(r.head()));
assert!(!Options().check(req.head()));
let r = TestRequest::default()
.method(Method::CONNECT)
.to_http_request();
assert!(Connect().check(&r));
assert!(!Connect().check(&req));
assert!(Connect().check(r.head()));
assert!(!Connect().check(req.head()));
let r = TestRequest::default()
.method(Method::PATCH)
.to_http_request();
assert!(Patch().check(&r));
assert!(!Patch().check(&req));
assert!(Patch().check(r.head()));
assert!(!Patch().check(req.head()));
let r = TestRequest::default()
.method(Method::TRACE)
.to_http_request();
assert!(Trace().check(&r));
assert!(!Trace().check(&req));
assert!(Trace().check(r.head()));
assert!(!Trace().check(req.head()));
}
#[test]
@ -384,13 +393,13 @@ mod tests {
.method(Method::TRACE)
.to_http_request();
assert!(Not(Get()).check(&r));
assert!(!Not(Trace()).check(&r));
assert!(Not(Get()).check(r.head()));
assert!(!Not(Trace()).check(r.head()));
assert!(All(Trace()).and(Trace()).check(&r));
assert!(!All(Get()).and(Trace()).check(&r));
assert!(All(Trace()).and(Trace()).check(r.head()));
assert!(!All(Get()).and(Trace()).check(r.head()));
assert!(Any(Get()).or(Trace()).check(&r));
assert!(!Any(Get()).or(Get()).check(&r));
assert!(Any(Get()).or(Trace()).check(r.head()));
assert!(!Any(Get()).or(Get()).check(r.head()));
}
}

View File

@ -113,7 +113,7 @@ where
fn call(&mut self, req: ServiceRequest<P>) -> Self::Future {
// negotiate content-encoding
let encoding = if let Some(val) = req.headers.get(ACCEPT_ENCODING) {
let encoding = if let Some(val) = req.headers().get(ACCEPT_ENCODING) {
if let Ok(enc) = val.to_str() {
AcceptEncoding::parse(enc, self.encoding)
} else {
@ -157,7 +157,7 @@ where
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
let resp = futures::try_ready!(self.fut.poll());
let enc = if let Some(enc) = resp.head().extensions().get::<Enc>() {
let enc = if let Some(enc) = resp.response().extensions().get::<Enc>() {
enc.0
} else {
self.encoding

View File

@ -51,7 +51,7 @@ use crate::error::{ResponseError, Result};
use crate::http::header::{self, HeaderName, HeaderValue};
use crate::http::{self, HttpTryFrom, Method, StatusCode, Uri};
use crate::service::{ServiceRequest, ServiceResponse};
use crate::{HttpMessage, HttpResponse};
use crate::HttpResponse;
/// A set of errors that can occur during processing CORS
#[derive(Debug, Display)]
@ -702,9 +702,9 @@ where
if self.inner.preflight && Method::OPTIONS == *req.method() {
if let Err(e) = self
.inner
.validate_origin(&req)
.and_then(|_| self.inner.validate_allowed_method(&req))
.and_then(|_| self.inner.validate_allowed_headers(&req))
.validate_origin(req.head())
.and_then(|_| self.inner.validate_allowed_method(req.head()))
.and_then(|_| self.inner.validate_allowed_headers(req.head()))
{
return Either::A(ok(req.error_response(e)));
}
@ -739,7 +739,7 @@ where
let _ = resp.header(header::ACCESS_CONTROL_ALLOW_HEADERS, headers);
})
.if_some(
self.inner.access_control_allow_origin(&req),
self.inner.access_control_allow_origin(req.head()),
|origin, resp| {
let _ = resp.header(header::ACCESS_CONTROL_ALLOW_ORIGIN, origin);
},
@ -762,7 +762,7 @@ where
Either::A(ok(req.into_response(res)))
} else if req.headers().contains_key(header::ORIGIN) {
// Only check requests with a origin header.
if let Err(e) = self.inner.validate_origin(&req) {
if let Err(e) = self.inner.validate_origin(req.head()) {
return Either::A(ok(req.error_response(e)));
}
@ -771,7 +771,7 @@ where
Either::B(Either::B(Box::new(self.service.call(req).and_then(
move |mut res| {
if let Some(origin) =
inner.access_control_allow_origin(&res.request())
inner.access_control_allow_origin(res.request().head())
{
res.headers_mut()
.insert(header::ACCESS_CONTROL_ALLOW_ORIGIN, origin.clone());
@ -869,8 +869,8 @@ mod tests {
.method(Method::OPTIONS)
.to_srv_request();
assert!(cors.inner.validate_allowed_method(&req).is_err());
assert!(cors.inner.validate_allowed_headers(&req).is_err());
assert!(cors.inner.validate_allowed_method(req.head()).is_err());
assert!(cors.inner.validate_allowed_headers(req.head()).is_err());
let resp = test::call_success(&mut cors, req);
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
@ -879,8 +879,8 @@ mod tests {
.method(Method::OPTIONS)
.to_srv_request();
assert!(cors.inner.validate_allowed_method(&req).is_err());
assert!(cors.inner.validate_allowed_headers(&req).is_err());
assert!(cors.inner.validate_allowed_method(req.head()).is_err());
assert!(cors.inner.validate_allowed_headers(req.head()).is_err());
let req = TestRequest::with_header("Origin", "https://www.example.com")
.header(header::ACCESS_CONTROL_REQUEST_METHOD, "POST")
@ -961,9 +961,9 @@ mod tests {
let req = TestRequest::with_header("Origin", "https://www.unknown.com")
.method(Method::GET)
.to_srv_request();
cors.inner.validate_origin(&req).unwrap();
cors.inner.validate_allowed_method(&req).unwrap();
cors.inner.validate_allowed_headers(&req).unwrap();
cors.inner.validate_origin(req.head()).unwrap();
cors.inner.validate_allowed_method(req.head()).unwrap();
cors.inner.validate_allowed_headers(req.head()).unwrap();
}
#[test]

View File

@ -10,7 +10,6 @@ use futures::{Async, Poll, Stream};
use crate::dev::Payload;
use crate::error::{Error, PayloadError};
use crate::service::ServiceRequest;
use crate::HttpMessage;
/// `Middleware` for decompressing request's payload.
/// `Decompress` middleware must be added with `App::chain()` method.

View File

@ -148,7 +148,7 @@ impl<P> FromRequest<P> for Identity {
#[inline]
fn from_request(req: &mut ServiceFromRequest<P>) -> Self::Future {
Ok(Identity(req.clone()))
Ok(Identity(req.request().clone()))
}
}
@ -507,7 +507,7 @@ mod tests {
let resp =
test::call_success(&mut srv, TestRequest::with_uri("/login").to_request());
assert_eq!(resp.status(), StatusCode::OK);
let c = resp.cookies().next().unwrap().to_owned();
let c = resp.response().cookies().next().unwrap().to_owned();
let resp = test::call_success(
&mut srv,

View File

@ -15,7 +15,7 @@ use time;
use crate::dev::{BodySize, MessageBody, ResponseBody};
use crate::error::{Error, Result};
use crate::service::{ServiceRequest, ServiceResponse};
use crate::{HttpMessage, HttpResponse};
use crate::HttpResponse;
/// `Middleware` for logging request and response info to the terminal.
///
@ -201,7 +201,7 @@ where
if let Some(ref mut format) = self.format {
for unit in &mut format.0 {
unit.render_response(&res);
unit.render_response(res.response());
}
}

View File

@ -1,6 +1,5 @@
use std::cell::{Ref, RefMut};
use std::fmt;
use std::ops::Deref;
use std::rc::Rc;
use actix_http::http::{HeaderMap, Method, Uri, Version};
@ -66,6 +65,12 @@ impl HttpRequest {
self.head().version
}
#[inline]
/// Returns request's headers.
pub fn headers(&self) -> &HeaderMap {
&self.head().headers
}
/// The target path of this Request.
#[inline]
pub fn path(&self) -> &str {
@ -111,6 +116,18 @@ impl HttpRequest {
}
}
/// Request extensions
#[inline]
pub fn extensions(&self) -> Ref<Extensions> {
self.head().extensions()
}
/// Mutable reference to a the request's extensions
#[inline]
pub fn extensions_mut(&self) -> RefMut<Extensions> {
self.head().extensions_mut()
}
/// Generate url for named resource
///
/// ```rust
@ -154,15 +171,7 @@ impl HttpRequest {
/// Get *ConnectionInfo* for the current request.
#[inline]
pub fn connection_info(&self) -> Ref<ConnectionInfo> {
ConnectionInfo::get(&*self, &*self.config())
}
}
impl Deref for HttpRequest {
type Target = RequestHead;
fn deref(&self) -> &RequestHead {
self.head()
ConnectionInfo::get(self.head(), &*self.config())
}
}
@ -219,7 +228,7 @@ impl<P> FromRequest<P> for HttpRequest {
#[inline]
fn from_request(req: &mut ServiceFromRequest<P>) -> Self::Future {
Ok(req.clone())
Ok(req.request().clone())
}
}

View File

@ -313,7 +313,7 @@ pub(crate) mod tests {
let req = TestRequest::with_uri("/some").to_request();
let resp = TestRequest::block_on(srv.call(req)).unwrap();
assert_eq!(resp.status(), StatusCode::OK);
match resp.body() {
match resp.response().body() {
ResponseBody::Body(Body::Bytes(ref b)) => {
let bytes: Bytes = b.clone().into();
assert_eq!(bytes, Bytes::from_static(b"some"));

View File

@ -693,7 +693,7 @@ mod tests {
let resp = block_on(srv.call(req)).unwrap();
assert_eq!(resp.status(), StatusCode::OK);
match resp.body() {
match resp.response().body() {
ResponseBody::Body(Body::Bytes(ref b)) => {
let bytes: Bytes = b.clone().into();
assert_eq!(bytes, Bytes::from_static(b"project: project1"));
@ -799,7 +799,7 @@ mod tests {
let resp = block_on(srv.call(req)).unwrap();
assert_eq!(resp.status(), StatusCode::CREATED);
match resp.body() {
match resp.response().body() {
ResponseBody::Body(Body::Bytes(ref b)) => {
let bytes: Bytes = b.clone().into();
assert_eq!(bytes, Bytes::from_static(b"project: project_1"));
@ -826,7 +826,7 @@ mod tests {
let resp = block_on(srv.call(req)).unwrap();
assert_eq!(resp.status(), StatusCode::CREATED);
match resp.body() {
match resp.response().body() {
ResponseBody::Body(Body::Bytes(ref b)) => {
let bytes: Bytes = b.clone().into();
assert_eq!(bytes, Bytes::from_static(b"project: test - 1"));

View File

@ -4,7 +4,7 @@ use std::marker::PhantomData;
use std::rc::Rc;
use actix_http::body::{Body, MessageBody, ResponseBody};
use actix_http::http::{HeaderMap, Method, Uri, Version};
use actix_http::http::{HeaderMap, Method, StatusCode, Uri, Version};
use actix_http::{
Error, Extensions, HttpMessage, Payload, PayloadStream, Request, RequestHead,
Response, ResponseHead,
@ -123,7 +123,13 @@ impl<P> ServiceRequest<P> {
}
#[inline]
/// Returns mutable Request's headers.
/// Returns request's headers.
pub fn headers(&self) -> &HeaderMap {
&self.head().headers
}
#[inline]
/// Returns mutable request's headers.
pub fn headers_mut(&mut self) -> &mut HeaderMap {
&mut self.head_mut().headers
}
@ -202,20 +208,6 @@ impl<P> HttpMessage for ServiceRequest<P> {
}
}
impl<P> std::ops::Deref for ServiceRequest<P> {
type Target = RequestHead;
fn deref(&self) -> &RequestHead {
self.req.head()
}
}
impl<P> std::ops::DerefMut for ServiceRequest<P> {
fn deref_mut(&mut self) -> &mut RequestHead {
self.head_mut()
}
}
impl<P> fmt::Debug for ServiceRequest<P> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
writeln!(
@ -255,11 +247,19 @@ impl<P> ServiceFromRequest<P> {
}
#[inline]
/// Get reference to inner HttpRequest
pub fn request(&self) -> &HttpRequest {
&self.req
}
#[inline]
/// Convert this request into a HttpRequest
pub fn into_request(self) -> HttpRequest {
self.req
}
#[inline]
/// Get match information for this request
pub fn match_info_mut(&mut self) -> &mut Path<Url> {
&mut self.req.path
}
@ -281,14 +281,6 @@ impl<P> ServiceFromRequest<P> {
}
}
impl<P> std::ops::Deref for ServiceFromRequest<P> {
type Target = HttpRequest;
fn deref(&self) -> &HttpRequest {
&self.req
}
}
impl<P> HttpMessage for ServiceFromRequest<P> {
type Stream = P;
@ -366,6 +358,24 @@ impl<B> ServiceResponse<B> {
&mut self.response
}
/// 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()
}
/// Execute closure and in case of error convert it to response.
pub fn checked_expr<F, E>(mut self, f: F) -> Self
where
@ -402,20 +412,6 @@ impl<B> ServiceResponse<B> {
}
}
impl<B> std::ops::Deref for ServiceResponse<B> {
type Target = Response<B>;
fn deref(&self) -> &Response<B> {
self.response()
}
}
impl<B> std::ops::DerefMut for ServiceResponse<B> {
fn deref_mut(&mut self) -> &mut Response<B> {
self.response_mut()
}
}
impl<B> Into<Response<B>> for ServiceResponse<B> {
fn into(self) -> Response<B> {
self.response

View File

@ -80,7 +80,7 @@ where
#[inline]
fn from_request(req: &mut ServiceFromRequest<P>) -> Self::Future {
let req2 = req.clone();
let req2 = req.request().clone();
let (limit, err) = req
.route_data::<FormConfig>()
.map(|c| (c.limit, c.ehandler.clone()))

View File

@ -174,7 +174,7 @@ where
#[inline]
fn from_request(req: &mut ServiceFromRequest<P>) -> Self::Future {
let req2 = req.clone();
let req2 = req.request().clone();
let (limit, err) = req
.route_data::<JsonConfig>()
.map(|c| (c.limit, c.ehandler.clone()))

View File

@ -170,7 +170,7 @@ where
#[inline]
fn from_request(req: &mut ServiceFromRequest<P>) -> Self::Future {
Self::extract(req).map_err(ErrorNotFound)
Self::extract(req.request()).map_err(ErrorNotFound)
}
}

View File

@ -119,7 +119,7 @@ where
#[inline]
fn from_request(req: &mut ServiceFromRequest<P>) -> Self::Future {
serde_urlencoded::from_str::<T>(req.query_string())
serde_urlencoded::from_str::<T>(req.request().query_string())
.map(|val| Ok(Query(val)))
.unwrap_or_else(|e| Err(e.into()))
}