From 8c2244dd889ce4a1f2e216b379661aa3a22806e5 Mon Sep 17 00:00:00 2001 From: Nikolay Kim Date: Fri, 5 Oct 2018 11:04:59 -0700 Subject: [PATCH] rename HttpResponse --- README.md | 2 +- src/error.rs | 133 +++++++------- src/h1/codec.rs | 6 +- src/h1/decoder.rs | 2 +- src/h1/dispatcher.rs | 8 +- src/h1/encoder.rs | 6 +- src/h1/service.rs | 10 +- src/httpcodes.rs | 12 +- src/httpmessage.rs | 16 +- src/json.rs | 6 +- src/lib.rs | 12 +- src/payload.rs | 2 +- src/{httpresponse.rs => response.rs} | 260 +++++++++++++-------------- src/test.rs | 22 +-- src/ws/mod.rs | 52 ++---- tests/test_h1v2.rs | 4 +- 16 files changed, 266 insertions(+), 287 deletions(-) rename src/{httpresponse.rs => response.rs} (81%) diff --git a/README.md b/README.md index 7ddd532e..b273ea8c 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# Actix http [![Build Status](https://travis-ci.org/fafhrd91/actix-http.svg?branch=master)](https://travis-ci.org/fafhrd91/actix-http) [![Build status](https://ci.appveyor.com/api/projects/status/kkdb4yce7qhm5w85/branch/master?svg=true)](https://ci.appveyor.com/project/fafhrd91/actix-web-hdy9d/branch/master) [![codecov](https://codecov.io/gh/actix/actix-web/branch/master/graph/badge.svg)](https://codecov.io/gh/actix/actix-web) [![crates.io](https://meritbadge.herokuapp.com/actix-web)](https://crates.io/crates/actix-web) [![Join the chat at https://gitter.im/actix/actix](https://badges.gitter.im/actix/actix.svg)](https://gitter.im/actix/actix?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) +# Actix http [![Build Status](https://travis-ci.org/fafhrd91/actix-http.svg?branch=master)](https://travis-ci.org/fafhrd91/actix-http) [![Build status](https://ci.appveyor.com/api/projects/status/kkdb4yce7qhm5w85/branch/master?svg=true)](https://ci.appveyor.com/project/fafhrd91/actix-web-hdy9d/branch/master) [![codecov](https://codecov.io/gh/fafhrd91/actix-http/branch/master/graph/badge.svg)](https://codecov.io/gh/fafhrd91/actix-http) [![crates.io](https://meritbadge.herokuapp.com/actix-web)](https://crates.io/crates/actix-web) [![Join the chat at https://gitter.im/actix/actix](https://badges.gitter.im/actix/actix.svg)](https://gitter.im/actix/actix?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) Actix http diff --git a/src/error.rs b/src/error.rs index fb5df232..dc2d45b8 100644 --- a/src/error.rs +++ b/src/error.rs @@ -21,8 +21,7 @@ pub use url::ParseError as UrlParseError; // re-exports pub use cookie::ParseError as CookieParseError; -// use httprequest::HttpRequest; -use httpresponse::{HttpResponse, HttpResponseParts}; +use response::{Response, ResponseParts}; /// A specialized [`Result`](https://doc.rust-lang.org/std/result/enum.Result.html) /// for actix web operations @@ -124,13 +123,13 @@ impl InternalResponseErrorAsFail for T { } } -/// Error that can be converted to `HttpResponse` +/// Error that can be converted to `Response` pub trait ResponseError: Fail + InternalResponseErrorAsFail { /// Create response for error /// /// Internal server error is generated by default. - fn error_response(&self) -> HttpResponse { - HttpResponse::new(StatusCode::INTERNAL_SERVER_ERROR) + fn error_response(&self) -> Response { + Response::new(StatusCode::INTERNAL_SERVER_ERROR) } } @@ -155,10 +154,10 @@ impl fmt::Debug for Error { } } -/// Convert `Error` to a `HttpResponse` instance -impl From for HttpResponse { +/// Convert `Error` to a `Response` instance +impl From for Response { fn from(err: Error) -> Self { - HttpResponse::from_error(err) + Response::from_error(err) } } @@ -202,15 +201,15 @@ impl ResponseError for UrlParseError {} /// Return `BAD_REQUEST` for `de::value::Error` impl ResponseError for DeError { - fn error_response(&self) -> HttpResponse { - HttpResponse::new(StatusCode::BAD_REQUEST) + fn error_response(&self) -> Response { + Response::new(StatusCode::BAD_REQUEST) } } /// Return `BAD_REQUEST` for `Utf8Error` impl ResponseError for Utf8Error { - fn error_response(&self) -> HttpResponse { - HttpResponse::new(StatusCode::BAD_REQUEST) + fn error_response(&self) -> Response { + Response::new(StatusCode::BAD_REQUEST) } } @@ -220,26 +219,26 @@ impl ResponseError for HttpError {} /// Return `InternalServerError` for `io::Error` impl ResponseError for io::Error { - fn error_response(&self) -> HttpResponse { + fn error_response(&self) -> Response { match self.kind() { - io::ErrorKind::NotFound => HttpResponse::new(StatusCode::NOT_FOUND), - io::ErrorKind::PermissionDenied => HttpResponse::new(StatusCode::FORBIDDEN), - _ => HttpResponse::new(StatusCode::INTERNAL_SERVER_ERROR), + io::ErrorKind::NotFound => Response::new(StatusCode::NOT_FOUND), + io::ErrorKind::PermissionDenied => Response::new(StatusCode::FORBIDDEN), + _ => Response::new(StatusCode::INTERNAL_SERVER_ERROR), } } } /// `BadRequest` for `InvalidHeaderValue` impl ResponseError for header::InvalidHeaderValue { - fn error_response(&self) -> HttpResponse { - HttpResponse::new(StatusCode::BAD_REQUEST) + fn error_response(&self) -> Response { + Response::new(StatusCode::BAD_REQUEST) } } /// `BadRequest` for `InvalidHeaderValue` impl ResponseError for header::InvalidHeaderValueBytes { - fn error_response(&self) -> HttpResponse { - HttpResponse::new(StatusCode::BAD_REQUEST) + fn error_response(&self) -> Response { + Response::new(StatusCode::BAD_REQUEST) } } @@ -288,8 +287,8 @@ pub enum ParseError { /// Return `BadRequest` for `ParseError` impl ResponseError for ParseError { - fn error_response(&self) -> HttpResponse { - HttpResponse::new(StatusCode::BAD_REQUEST) + fn error_response(&self) -> Response { + Response::new(StatusCode::BAD_REQUEST) } } @@ -362,18 +361,18 @@ impl From for PayloadError { /// - `Overflow` returns `PayloadTooLarge` /// - Other errors returns `BadRequest` impl ResponseError for PayloadError { - fn error_response(&self) -> HttpResponse { + fn error_response(&self) -> Response { match *self { - PayloadError::Overflow => HttpResponse::new(StatusCode::PAYLOAD_TOO_LARGE), - _ => HttpResponse::new(StatusCode::BAD_REQUEST), + PayloadError::Overflow => Response::new(StatusCode::PAYLOAD_TOO_LARGE), + _ => Response::new(StatusCode::BAD_REQUEST), } } } /// Return `BadRequest` for `cookie::ParseError` impl ResponseError for cookie::ParseError { - fn error_response(&self) -> HttpResponse { - HttpResponse::new(StatusCode::BAD_REQUEST) + fn error_response(&self) -> Response { + Response::new(StatusCode::BAD_REQUEST) } } @@ -443,8 +442,8 @@ pub enum ContentTypeError { /// Return `BadRequest` for `ContentTypeError` impl ResponseError for ContentTypeError { - fn error_response(&self) -> HttpResponse { - HttpResponse::new(StatusCode::BAD_REQUEST) + fn error_response(&self) -> Response { + Response::new(StatusCode::BAD_REQUEST) } } @@ -475,15 +474,11 @@ pub enum UrlencodedError { /// Return `BadRequest` for `UrlencodedError` impl ResponseError for UrlencodedError { - fn error_response(&self) -> HttpResponse { + fn error_response(&self) -> Response { match *self { - UrlencodedError::Overflow => { - HttpResponse::new(StatusCode::PAYLOAD_TOO_LARGE) - } - UrlencodedError::UnknownLength => { - HttpResponse::new(StatusCode::LENGTH_REQUIRED) - } - _ => HttpResponse::new(StatusCode::BAD_REQUEST), + UrlencodedError::Overflow => Response::new(StatusCode::PAYLOAD_TOO_LARGE), + UrlencodedError::UnknownLength => Response::new(StatusCode::LENGTH_REQUIRED), + _ => Response::new(StatusCode::BAD_REQUEST), } } } @@ -513,12 +508,10 @@ pub enum JsonPayloadError { /// Return `BadRequest` for `UrlencodedError` impl ResponseError for JsonPayloadError { - fn error_response(&self) -> HttpResponse { + fn error_response(&self) -> Response { match *self { - JsonPayloadError::Overflow => { - HttpResponse::new(StatusCode::PAYLOAD_TOO_LARGE) - } - _ => HttpResponse::new(StatusCode::BAD_REQUEST), + JsonPayloadError::Overflow => Response::new(StatusCode::PAYLOAD_TOO_LARGE), + _ => Response::new(StatusCode::BAD_REQUEST), } } } @@ -606,7 +599,7 @@ pub struct InternalError { enum InternalErrorType { Status(StatusCode), - Response(Box>>), + Response(Box>>), } impl InternalError { @@ -619,8 +612,8 @@ impl InternalError { } } - /// Create `InternalError` with predefined `HttpResponse`. - pub fn from_response(cause: T, response: HttpResponse) -> Self { + /// Create `InternalError` with predefined `Response`. + pub fn from_response(cause: T, response: Response) -> Self { let resp = response.into_parts(); InternalError { cause, @@ -661,14 +654,14 @@ impl ResponseError for InternalError where T: Send + Sync + fmt::Debug + fmt::Display + 'static, { - fn error_response(&self) -> HttpResponse { + fn error_response(&self) -> Response { match self.status { - InternalErrorType::Status(st) => HttpResponse::new(st), + InternalErrorType::Status(st) => Response::new(st), InternalErrorType::Response(ref resp) => { if let Some(resp) = resp.lock().unwrap().take() { - HttpResponse::from_parts(resp) + Response::from_parts(resp) } else { - HttpResponse::new(StatusCode::INTERNAL_SERVER_ERROR) + Response::new(StatusCode::INTERNAL_SERVER_ERROR) } } } @@ -838,14 +831,14 @@ mod tests { #[test] fn test_into_response() { - let resp: HttpResponse = ParseError::Incomplete.error_response(); + let resp: Response = ParseError::Incomplete.error_response(); assert_eq!(resp.status(), StatusCode::BAD_REQUEST); - let resp: HttpResponse = CookieParseError::EmptyName.error_response(); + let resp: Response = CookieParseError::EmptyName.error_response(); assert_eq!(resp.status(), StatusCode::BAD_REQUEST); let err: HttpError = StatusCode::from_u16(10000).err().unwrap().into(); - let resp: HttpResponse = err.error_response(); + let resp: Response = err.error_response(); assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR); } @@ -883,7 +876,7 @@ mod tests { fn test_error_http_response() { let orig = io::Error::new(io::ErrorKind::Other, "other"); let e = Error::from(orig); - let resp: HttpResponse = e.into(); + let resp: Response = e.into(); assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR); } @@ -944,8 +937,8 @@ mod tests { #[test] fn test_internal_error() { let err = - InternalError::from_response(ParseError::Method, HttpResponse::Ok().into()); - let resp: HttpResponse = err.error_response(); + InternalError::from_response(ParseError::Method, Response::Ok().into()); + let resp: Response = err.error_response(); assert_eq!(resp.status(), StatusCode::OK); } @@ -977,49 +970,49 @@ mod tests { #[test] fn test_error_helpers() { - let r: HttpResponse = ErrorBadRequest("err").into(); + let r: Response = ErrorBadRequest("err").into(); assert_eq!(r.status(), StatusCode::BAD_REQUEST); - let r: HttpResponse = ErrorUnauthorized("err").into(); + let r: Response = ErrorUnauthorized("err").into(); assert_eq!(r.status(), StatusCode::UNAUTHORIZED); - let r: HttpResponse = ErrorForbidden("err").into(); + let r: Response = ErrorForbidden("err").into(); assert_eq!(r.status(), StatusCode::FORBIDDEN); - let r: HttpResponse = ErrorNotFound("err").into(); + let r: Response = ErrorNotFound("err").into(); assert_eq!(r.status(), StatusCode::NOT_FOUND); - let r: HttpResponse = ErrorMethodNotAllowed("err").into(); + let r: Response = ErrorMethodNotAllowed("err").into(); assert_eq!(r.status(), StatusCode::METHOD_NOT_ALLOWED); - let r: HttpResponse = ErrorRequestTimeout("err").into(); + let r: Response = ErrorRequestTimeout("err").into(); assert_eq!(r.status(), StatusCode::REQUEST_TIMEOUT); - let r: HttpResponse = ErrorConflict("err").into(); + let r: Response = ErrorConflict("err").into(); assert_eq!(r.status(), StatusCode::CONFLICT); - let r: HttpResponse = ErrorGone("err").into(); + let r: Response = ErrorGone("err").into(); assert_eq!(r.status(), StatusCode::GONE); - let r: HttpResponse = ErrorPreconditionFailed("err").into(); + let r: Response = ErrorPreconditionFailed("err").into(); assert_eq!(r.status(), StatusCode::PRECONDITION_FAILED); - let r: HttpResponse = ErrorExpectationFailed("err").into(); + let r: Response = ErrorExpectationFailed("err").into(); assert_eq!(r.status(), StatusCode::EXPECTATION_FAILED); - let r: HttpResponse = ErrorInternalServerError("err").into(); + let r: Response = ErrorInternalServerError("err").into(); assert_eq!(r.status(), StatusCode::INTERNAL_SERVER_ERROR); - let r: HttpResponse = ErrorNotImplemented("err").into(); + let r: Response = ErrorNotImplemented("err").into(); assert_eq!(r.status(), StatusCode::NOT_IMPLEMENTED); - let r: HttpResponse = ErrorBadGateway("err").into(); + let r: Response = ErrorBadGateway("err").into(); assert_eq!(r.status(), StatusCode::BAD_GATEWAY); - let r: HttpResponse = ErrorServiceUnavailable("err").into(); + let r: Response = ErrorServiceUnavailable("err").into(); assert_eq!(r.status(), StatusCode::SERVICE_UNAVAILABLE); - let r: HttpResponse = ErrorGatewayTimeout("err").into(); + let r: Response = ErrorGatewayTimeout("err").into(); assert_eq!(r.status(), StatusCode::GATEWAY_TIMEOUT); } } diff --git a/src/h1/codec.rs b/src/h1/codec.rs index 40d0a240..a27e6472 100644 --- a/src/h1/codec.rs +++ b/src/h1/codec.rs @@ -12,8 +12,8 @@ use error::ParseError; use helpers; use http::header::{HeaderValue, CONNECTION, CONTENT_LENGTH, DATE, TRANSFER_ENCODING}; use http::{Method, Version}; -use httpresponse::HttpResponse; use request::RequestPool; +use response::Response; bitflags! { struct Flags: u8 { @@ -29,7 +29,7 @@ const AVERAGE_HEADER_SIZE: usize = 30; /// Http response pub enum OutMessage { /// Http response message - Response(HttpResponse), + Response(Response), /// Payload chunk Payload(Bytes), } @@ -87,7 +87,7 @@ impl Codec { } fn encode_response( - &mut self, mut msg: HttpResponse, buffer: &mut BytesMut, + &mut self, mut msg: Response, buffer: &mut BytesMut, ) -> io::Result<()> { // prepare transfer encoding self.te diff --git a/src/h1/decoder.rs b/src/h1/decoder.rs index 90946b45..48776226 100644 --- a/src/h1/decoder.rs +++ b/src/h1/decoder.rs @@ -628,7 +628,7 @@ mod tests { // let buf = Buffer::new("GET /test HTTP/1\r\n\r\n"); // let readbuf = BytesMut::new(); - // let mut h1 = Dispatcher::new(buf, |req| ok(HttpResponse::Ok().finish())); + // let mut h1 = Dispatcher::new(buf, |req| ok(Response::Ok().finish())); // assert!(h1.poll_io().is_ok()); // assert!(h1.poll_io().is_ok()); // assert!(h1.flags.contains(Flags::READ_DISCONNECTED)); diff --git a/src/h1/dispatcher.rs b/src/h1/dispatcher.rs index 18309402..728a78b9 100644 --- a/src/h1/dispatcher.rs +++ b/src/h1/dispatcher.rs @@ -17,8 +17,8 @@ use body::Body; use config::ServiceConfig; use error::DispatchError; use framed::Framed; -use httpresponse::HttpResponse; use request::Request; +use response::Response; use super::codec::{Codec, InMessage, OutMessage}; @@ -77,7 +77,7 @@ impl State { impl Dispatcher where T: AsyncRead + AsyncWrite, - S: Service, + S: Service, S::Error: Debug + Display, { /// Create http/1 dispatcher. @@ -415,7 +415,7 @@ where .insert(Flags::STARTED | Flags::READ_DISCONNECTED); self.state = State::SendResponse(Some(OutMessage::Response( - HttpResponse::RequestTimeout().finish(), + Response::RequestTimeout().finish(), ))); } else { trace!("Keep-alive timeout, close connection"); @@ -452,7 +452,7 @@ where impl Future for Dispatcher where T: AsyncRead + AsyncWrite, - S: Service, + S: Service, S::Error: Debug + Display, { type Item = (); diff --git a/src/h1/encoder.rs b/src/h1/encoder.rs index d1758735..1544b240 100644 --- a/src/h1/encoder.rs +++ b/src/h1/encoder.rs @@ -11,8 +11,8 @@ use http::{StatusCode, Version}; use body::{Binary, Body}; use header::ContentEncoding; use http::Method; -use httpresponse::HttpResponse; use request::Request; +use response::Response; #[derive(Debug)] pub(crate) enum ResponseLength { @@ -41,7 +41,7 @@ impl Default for ResponseEncoder { } impl ResponseEncoder { - pub fn update(&mut self, resp: &mut HttpResponse, head: bool, version: Version) { + pub fn update(&mut self, resp: &mut Response, head: bool, version: Version) { self.head = head; let version = resp.version().unwrap_or_else(|| version); @@ -98,7 +98,7 @@ impl ResponseEncoder { } fn streaming_encoding( - &mut self, version: Version, resp: &mut HttpResponse, + &mut self, version: Version, resp: &mut Response, ) -> TransferEncoding { match resp.chunked() { Some(true) => { diff --git a/src/h1/service.rs b/src/h1/service.rs index 436e77a5..8038c9fb 100644 --- a/src/h1/service.rs +++ b/src/h1/service.rs @@ -7,8 +7,8 @@ use tokio_io::{AsyncRead, AsyncWrite}; use config::ServiceConfig; use error::DispatchError; -use httpresponse::HttpResponse; use request::Request; +use response::Response; use super::dispatcher::Dispatcher; @@ -36,7 +36,7 @@ where impl NewService for H1Service where T: AsyncRead + AsyncWrite, - S: NewService + Clone, + S: NewService + Clone, S::Service: Clone, S::Error: Debug + Display, { @@ -65,7 +65,7 @@ pub struct H1ServiceResponse { impl Future for H1ServiceResponse where T: AsyncRead + AsyncWrite, - S: NewService, + S: NewService, S::Service: Clone, S::Error: Debug + Display, { @@ -90,7 +90,7 @@ pub struct H1ServiceHandler { impl H1ServiceHandler where - S: Service + Clone, + S: Service + Clone, S::Error: Debug + Display, { fn new(cfg: ServiceConfig, srv: S) -> H1ServiceHandler { @@ -105,7 +105,7 @@ where impl Service for H1ServiceHandler where T: AsyncRead + AsyncWrite, - S: Service + Clone, + S: Service + Clone, S::Error: Debug + Display, { type Request = T; diff --git a/src/httpcodes.rs b/src/httpcodes.rs index 41e57d1e..7d42a1cc 100644 --- a/src/httpcodes.rs +++ b/src/httpcodes.rs @@ -1,18 +1,18 @@ //! Basic http responses #![allow(non_upper_case_globals)] use http::StatusCode; -use httpresponse::{HttpResponse, HttpResponseBuilder}; +use response::{Response, ResponseBuilder}; macro_rules! STATIC_RESP { ($name:ident, $status:expr) => { #[allow(non_snake_case, missing_docs)] - pub fn $name() -> HttpResponseBuilder { - HttpResponse::build($status) + pub fn $name() -> ResponseBuilder { + Response::build($status) } }; } -impl HttpResponse { +impl Response { STATIC_RESP!(Ok, StatusCode::OK); STATIC_RESP!(Created, StatusCode::CREATED); STATIC_RESP!(Accepted, StatusCode::ACCEPTED); @@ -74,11 +74,11 @@ impl HttpResponse { mod tests { use body::Body; use http::StatusCode; - use httpresponse::HttpResponse; + use response::Response; #[test] fn test_build() { - let resp = HttpResponse::Ok().body(Body::Empty); + let resp = Response::Ok().body(Body::Empty); assert_eq!(resp.status(), StatusCode::OK); } } diff --git a/src/httpmessage.rs b/src/httpmessage.rs index 531aa1a7..f68f3650 100644 --- a/src/httpmessage.rs +++ b/src/httpmessage.rs @@ -112,18 +112,18 @@ pub trait HttpMessage: Sized { /// # extern crate futures; /// # #[macro_use] extern crate serde_derive; /// use actix_web::{ - /// AsyncResponder, FutureResponse, HttpMessage, HttpRequest, HttpResponse, + /// AsyncResponder, FutureResponse, HttpMessage, HttpRequest, Response, /// }; /// use bytes::Bytes; /// use futures::future::Future; /// - /// fn index(mut req: HttpRequest) -> FutureResponse { + /// fn index(mut req: HttpRequest) -> FutureResponse { /// req.body() // <- get Body future /// .limit(1024) // <- change max size of the body to a 1kb /// .from_err() /// .and_then(|bytes: Bytes| { // <- complete body /// println!("==== BODY ==== {:?}", bytes); - /// Ok(HttpResponse::Ok().into()) + /// Ok(Response::Ok().into()) /// }).responder() /// } /// # fn main() {} @@ -148,15 +148,15 @@ pub trait HttpMessage: Sized { /// # extern crate futures; /// # use futures::Future; /// # use std::collections::HashMap; - /// use actix_web::{FutureResponse, HttpMessage, HttpRequest, HttpResponse}; + /// use actix_web::{FutureResponse, HttpMessage, HttpRequest, Response}; /// - /// fn index(mut req: HttpRequest) -> FutureResponse { + /// fn index(mut req: HttpRequest) -> FutureResponse { /// Box::new( /// req.urlencoded::>() // <- get UrlEncoded future /// .from_err() /// .and_then(|params| { // <- url encoded parameters /// println!("==== BODY ==== {:?}", params); - /// Ok(HttpResponse::Ok().into()) + /// Ok(Response::Ok().into()) /// }), /// ) /// } @@ -188,12 +188,12 @@ pub trait HttpMessage: Sized { /// name: String, /// } /// - /// fn index(mut req: HttpRequest) -> Box> { + /// fn index(mut req: HttpRequest) -> Box> { /// req.json() // <- get JsonBody future /// .from_err() /// .and_then(|val: MyObj| { // <- deserialized value /// println!("==== BODY ==== {:?}", val); - /// Ok(HttpResponse::Ok().into()) + /// Ok(Response::Ok().into()) /// }).responder() /// } /// # fn main() {} diff --git a/src/json.rs b/src/json.rs index 5c64b9bd..a5288489 100644 --- a/src/json.rs +++ b/src/json.rs @@ -123,7 +123,7 @@ where /// # extern crate actix_web; /// # extern crate futures; /// # #[macro_use] extern crate serde_derive; -/// use actix_web::{AsyncResponder, Error, HttpMessage, HttpRequest, HttpResponse}; +/// use actix_web::{AsyncResponder, Error, HttpMessage, HttpRequest, Response}; /// use futures::future::Future; /// /// #[derive(Deserialize, Debug)] @@ -131,12 +131,12 @@ where /// name: String, /// } /// -/// fn index(mut req: HttpRequest) -> Box> { +/// fn index(mut req: HttpRequest) -> Box> { /// req.json() // <- get JsonBody future /// .from_err() /// .and_then(|val: MyObj| { // <- deserialized value /// println!("==== BODY ==== {:?}", val); -/// Ok(HttpResponse::Ok().into()) +/// Ok(Response::Ok().into()) /// }).responder() /// } /// # fn main() {} diff --git a/src/lib.rs b/src/lib.rs index ae5a9f95..74e7ced7 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -41,8 +41,8 @@ //! represents an HTTP server instance and is used to instantiate and //! configure servers. //! -//! * [HttpRequest](struct.HttpRequest.html) and -//! [HttpResponse](struct.HttpResponse.html): These structs +//! * [Request](struct.Request.html) and +//! [Response](struct.Response.html): These structs //! represent HTTP requests and responses and expose various methods //! for inspecting, creating and otherwise utilizing them. //! @@ -129,10 +129,10 @@ mod extensions; mod header; mod httpcodes; mod httpmessage; -mod httpresponse; mod json; mod payload; mod request; +mod response; mod uri; #[doc(hidden)] @@ -147,9 +147,9 @@ pub use body::{Binary, Body}; pub use error::{Error, ResponseError, Result}; pub use extensions::Extensions; pub use httpmessage::HttpMessage; -pub use httpresponse::HttpResponse; pub use json::Json; pub use request::Request; +pub use response::Response; pub use self::config::{KeepAlive, ServiceConfig, ServiceConfigBuilder}; @@ -166,9 +166,9 @@ pub mod dev { pub use body::BodyStream; pub use httpmessage::{MessageBody, Readlines, UrlEncoded}; - pub use httpresponse::HttpResponseBuilder; pub use json::JsonBody; pub use payload::{Payload, PayloadBuffer}; + pub use response::ResponseBuilder; } pub mod http { @@ -187,5 +187,5 @@ pub mod http { pub use header::*; } pub use header::ContentEncoding; - pub use httpresponse::ConnectionType; + pub use response::ConnectionType; } diff --git a/src/payload.rs b/src/payload.rs index 2131e3c3..3f51f6ec 100644 --- a/src/payload.rs +++ b/src/payload.rs @@ -27,7 +27,7 @@ pub(crate) enum PayloadStatus { /// `.readany()` method. Payload stream is not thread safe. Payload does not /// notify current task when new data is available. /// -/// Payload stream can be used as `HttpResponse` body stream. +/// Payload stream can be used as `Response` body stream. #[derive(Debug)] pub struct Payload { inner: Rc>, diff --git a/src/httpresponse.rs b/src/response.rs similarity index 81% rename from src/httpresponse.rs rename to src/response.rs index 3c034fae..d0136b40 100644 --- a/src/httpresponse.rs +++ b/src/response.rs @@ -31,54 +31,54 @@ pub enum ConnectionType { } /// An HTTP Response -pub struct HttpResponse(Box, &'static HttpResponsePool); +pub struct Response(Box, &'static ResponsePool); -impl HttpResponse { +impl Response { #[inline] - fn get_ref(&self) -> &InnerHttpResponse { + fn get_ref(&self) -> &InnerResponse { self.0.as_ref() } #[inline] - fn get_mut(&mut self) -> &mut InnerHttpResponse { + fn get_mut(&mut self) -> &mut InnerResponse { self.0.as_mut() } /// Create http response builder with specific status. #[inline] - pub fn build(status: StatusCode) -> HttpResponseBuilder { - HttpResponsePool::get(status) + pub fn build(status: StatusCode) -> ResponseBuilder { + ResponsePool::get(status) } /// Create http response builder #[inline] - pub fn build_from>(source: T) -> HttpResponseBuilder { + pub fn build_from>(source: T) -> ResponseBuilder { source.into() } /// Constructs a response #[inline] - pub fn new(status: StatusCode) -> HttpResponse { - HttpResponsePool::with_body(status, Body::Empty) + pub fn new(status: StatusCode) -> Response { + ResponsePool::with_body(status, Body::Empty) } /// Constructs a response with body #[inline] - pub fn with_body>(status: StatusCode, body: B) -> HttpResponse { - HttpResponsePool::with_body(status, body.into()) + pub fn with_body>(status: StatusCode, body: B) -> Response { + ResponsePool::with_body(status, body.into()) } /// Constructs an error response #[inline] - pub fn from_error(error: Error) -> HttpResponse { + pub fn from_error(error: Error) -> Response { let mut resp = error.as_response_error().error_response(); resp.get_mut().error = Some(error); resp } - /// Convert `HttpResponse` to a `HttpResponseBuilder` + /// Convert `Response` to a `ResponseBuilder` #[inline] - pub fn into_builder(self) -> HttpResponseBuilder { + pub fn into_builder(self) -> ResponseBuilder { // If this response has cookies, load them into a jar let mut jar: Option = None; for c in self.cookies() { @@ -91,7 +91,7 @@ impl HttpResponse { } } - HttpResponseBuilder { + ResponseBuilder { pool: self.1, response: Some(self.0), err: None, @@ -282,23 +282,23 @@ impl HttpResponse { self.1.release(self.0); } - pub(crate) fn into_parts(self) -> HttpResponseParts { + pub(crate) fn into_parts(self) -> ResponseParts { self.0.into_parts() } - pub(crate) fn from_parts(parts: HttpResponseParts) -> HttpResponse { - HttpResponse( - Box::new(InnerHttpResponse::from_parts(parts)), - HttpResponsePool::get_pool(), + pub(crate) fn from_parts(parts: ResponseParts) -> Response { + Response( + Box::new(InnerResponse::from_parts(parts)), + ResponsePool::get_pool(), ) } } -impl fmt::Debug for HttpResponse { +impl fmt::Debug for Response { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let res = writeln!( f, - "\nHttpResponse {:?} {}{}", + "\nResponse {:?} {}{}", self.get_ref().version, self.get_ref().status, self.get_ref().reason.unwrap_or("") @@ -332,16 +332,16 @@ impl<'a> Iterator for CookieIter<'a> { /// An HTTP response builder /// -/// This type can be used to construct an instance of `HttpResponse` through a +/// This type can be used to construct an instance of `Response` through a /// builder-like pattern. -pub struct HttpResponseBuilder { - pool: &'static HttpResponsePool, - response: Option>, +pub struct ResponseBuilder { + pool: &'static ResponsePool, + response: Option>, err: Option, cookies: Option, } -impl HttpResponseBuilder { +impl ResponseBuilder { /// Set HTTP status code of this response. #[inline] pub fn status(&mut self, status: StatusCode) -> &mut Self { @@ -366,10 +366,10 @@ impl HttpResponseBuilder { /// /// ```rust,ignore /// # extern crate actix_web; - /// use actix_web::{http, HttpRequest, HttpResponse, Result}; + /// use actix_web::{http, Request, Response, Result}; /// - /// fn index(req: HttpRequest) -> Result { - /// Ok(HttpResponse::Ok() + /// fn index(req: HttpRequest) -> Result { + /// Ok(Response::Ok() /// .set(http::header::IfModifiedSince( /// "Sun, 07 Nov 1994 08:48:37 GMT".parse()?, /// )) @@ -394,10 +394,10 @@ impl HttpResponseBuilder { /// /// ```rust,ignore /// # extern crate actix_web; - /// use actix_web::{http, HttpRequest, HttpResponse}; + /// use actix_web::{http, Request, Response}; /// - /// fn index(req: HttpRequest) -> HttpResponse { - /// HttpResponse::Ok() + /// fn index(req: HttpRequest) -> Response { + /// Response::Ok() /// .header("X-TEST", "value") /// .header(http::header::CONTENT_TYPE, "application/json") /// .finish() @@ -516,10 +516,10 @@ impl HttpResponseBuilder { /// /// ```rust,ignore /// # extern crate actix_web; - /// use actix_web::{http, HttpRequest, HttpResponse, Result}; + /// use actix_web::{http, HttpRequest, Response, Result}; /// - /// fn index(req: HttpRequest) -> HttpResponse { - /// HttpResponse::Ok() + /// fn index(req: HttpRequest) -> Response { + /// Response::Ok() /// .cookie( /// http::Cookie::build("name", "value") /// .domain("www.rust-lang.org") @@ -546,10 +546,10 @@ impl HttpResponseBuilder { /// /// ```rust,ignore /// # extern crate actix_web; - /// use actix_web::{http, HttpRequest, HttpResponse, Result}; + /// use actix_web::{http, HttpRequest, Response, Result}; /// - /// fn index(req: &HttpRequest) -> HttpResponse { - /// let mut builder = HttpResponse::Ok(); + /// fn index(req: &HttpRequest) -> Response { + /// let mut builder = Response::Ok(); /// /// if let Some(ref cookie) = req.cookie("name") { /// builder.del_cookie(cookie); @@ -575,7 +575,7 @@ impl HttpResponseBuilder { /// true. pub fn if_true(&mut self, value: bool, f: F) -> &mut Self where - F: FnOnce(&mut HttpResponseBuilder), + F: FnOnce(&mut ResponseBuilder), { if value { f(self); @@ -587,7 +587,7 @@ impl HttpResponseBuilder { /// Some. pub fn if_some(&mut self, value: Option, f: F) -> &mut Self where - F: FnOnce(T, &mut HttpResponseBuilder), + F: FnOnce(T, &mut ResponseBuilder), { if let Some(val) = value { f(val, self); @@ -609,10 +609,10 @@ impl HttpResponseBuilder { self } - /// Set a body and generate `HttpResponse`. + /// Set a body and generate `Response`. /// - /// `HttpResponseBuilder` can not be used after this call. - pub fn body>(&mut self, body: B) -> HttpResponse { + /// `ResponseBuilder` can not be used after this call. + pub fn body>(&mut self, body: B) -> Response { if let Some(e) = self.err.take() { return Error::from(e).into(); } @@ -626,14 +626,14 @@ impl HttpResponseBuilder { } } response.body = body.into(); - HttpResponse(response, self.pool) + Response(response, self.pool) } #[inline] - /// Set a streaming body and generate `HttpResponse`. + /// Set a streaming body and generate `Response`. /// - /// `HttpResponseBuilder` can not be used after this call. - pub fn streaming(&mut self, stream: S) -> HttpResponse + /// `ResponseBuilder` can not be used after this call. + pub fn streaming(&mut self, stream: S) -> Response where S: Stream + 'static, E: Into, @@ -641,17 +641,17 @@ impl HttpResponseBuilder { self.body(Body::Streaming(Box::new(stream.map_err(|e| e.into())))) } - /// Set a json body and generate `HttpResponse` + /// Set a json body and generate `Response` /// - /// `HttpResponseBuilder` can not be used after this call. - pub fn json(&mut self, value: T) -> HttpResponse { + /// `ResponseBuilder` can not be used after this call. + pub fn json(&mut self, value: T) -> Response { self.json2(&value) } - /// Set a json body and generate `HttpResponse` + /// Set a json body and generate `Response` /// - /// `HttpResponseBuilder` can not be used after this call. - pub fn json2(&mut self, value: &T) -> HttpResponse { + /// `ResponseBuilder` can not be used after this call. + pub fn json2(&mut self, value: &T) -> Response { match serde_json::to_string(value) { Ok(body) => { let contains = if let Some(parts) = parts(&mut self.response, &self.err) @@ -671,16 +671,16 @@ impl HttpResponseBuilder { } #[inline] - /// Set an empty body and generate `HttpResponse` + /// Set an empty body and generate `Response` /// - /// `HttpResponseBuilder` can not be used after this call. - pub fn finish(&mut self) -> HttpResponse { + /// `ResponseBuilder` can not be used after this call. + pub fn finish(&mut self) -> Response { self.body(Body::Empty) } - /// This method construct new `HttpResponseBuilder` - pub fn take(&mut self) -> HttpResponseBuilder { - HttpResponseBuilder { + /// This method construct new `ResponseBuilder` + pub fn take(&mut self) -> ResponseBuilder { + ResponseBuilder { pool: self.pool, response: self.response.take(), err: self.err.take(), @@ -692,8 +692,8 @@ impl HttpResponseBuilder { #[inline] #[cfg_attr(feature = "cargo-clippy", allow(clippy::borrowed_box))] fn parts<'a>( - parts: &'a mut Option>, err: &Option, -) -> Option<&'a mut Box> { + parts: &'a mut Option>, err: &Option, +) -> Option<&'a mut Box> { if err.is_some() { return None; } @@ -701,7 +701,7 @@ fn parts<'a>( } /// Helper converters -impl, E: Into> From> for HttpResponse { +impl, E: Into> From> for Response { fn from(res: Result) -> Self { match res { Ok(val) => val.into(), @@ -710,62 +710,62 @@ impl, E: Into> From> for HttpResponse } } -impl From for HttpResponse { - fn from(mut builder: HttpResponseBuilder) -> Self { +impl From for Response { + fn from(mut builder: ResponseBuilder) -> Self { builder.finish() } } -impl From<&'static str> for HttpResponse { +impl From<&'static str> for Response { fn from(val: &'static str) -> Self { - HttpResponse::Ok() + Response::Ok() .content_type("text/plain; charset=utf-8") .body(val) } } -impl From<&'static [u8]> for HttpResponse { +impl From<&'static [u8]> for Response { fn from(val: &'static [u8]) -> Self { - HttpResponse::Ok() + Response::Ok() .content_type("application/octet-stream") .body(val) } } -impl From for HttpResponse { +impl From for Response { fn from(val: String) -> Self { - HttpResponse::Ok() + Response::Ok() .content_type("text/plain; charset=utf-8") .body(val) } } -impl<'a> From<&'a String> for HttpResponse { +impl<'a> From<&'a String> for Response { fn from(val: &'a String) -> Self { - HttpResponse::build(StatusCode::OK) + Response::build(StatusCode::OK) .content_type("text/plain; charset=utf-8") .body(val) } } -impl From for HttpResponse { +impl From for Response { fn from(val: Bytes) -> Self { - HttpResponse::Ok() + Response::Ok() .content_type("application/octet-stream") .body(val) } } -impl From for HttpResponse { +impl From for Response { fn from(val: BytesMut) -> Self { - HttpResponse::Ok() + Response::Ok() .content_type("application/octet-stream") .body(val) } } #[derive(Debug)] -struct InnerHttpResponse { +struct InnerResponse { version: Option, headers: HeaderMap, status: StatusCode, @@ -779,7 +779,7 @@ struct InnerHttpResponse { error: Option, } -pub(crate) struct HttpResponseParts { +pub(crate) struct ResponseParts { version: Option, headers: HeaderMap, status: StatusCode, @@ -790,10 +790,10 @@ pub(crate) struct HttpResponseParts { error: Option, } -impl InnerHttpResponse { +impl InnerResponse { #[inline] - fn new(status: StatusCode, body: Body) -> InnerHttpResponse { - InnerHttpResponse { + fn new(status: StatusCode, body: Body) -> InnerResponse { + InnerResponse { status, body, version: None, @@ -809,7 +809,7 @@ impl InnerHttpResponse { } /// This is for failure, we can not have Send + Sync on Streaming and Actor response - fn into_parts(mut self) -> HttpResponseParts { + fn into_parts(mut self) -> ResponseParts { let body = match mem::replace(&mut self.body, Body::Empty) { Body::Empty => None, Body::Binary(mut bin) => Some(bin.take()), @@ -819,7 +819,7 @@ impl InnerHttpResponse { } }; - HttpResponseParts { + ResponseParts { body, version: self.version, headers: self.headers, @@ -831,14 +831,14 @@ impl InnerHttpResponse { } } - fn from_parts(parts: HttpResponseParts) -> InnerHttpResponse { + fn from_parts(parts: ResponseParts) -> InnerResponse { let body = if let Some(ref body) = parts.body { Body::Binary(body.clone().into()) } else { Body::Empty }; - InnerHttpResponse { + InnerResponse { body, status: parts.status, version: parts.version, @@ -855,35 +855,35 @@ impl InnerHttpResponse { } /// Internal use only! -pub(crate) struct HttpResponsePool(RefCell>>); +pub(crate) struct ResponsePool(RefCell>>); -thread_local!(static POOL: &'static HttpResponsePool = HttpResponsePool::pool()); +thread_local!(static POOL: &'static ResponsePool = ResponsePool::pool()); -impl HttpResponsePool { - fn pool() -> &'static HttpResponsePool { - let pool = HttpResponsePool(RefCell::new(VecDeque::with_capacity(128))); +impl ResponsePool { + fn pool() -> &'static ResponsePool { + let pool = ResponsePool(RefCell::new(VecDeque::with_capacity(128))); Box::leak(Box::new(pool)) } - pub fn get_pool() -> &'static HttpResponsePool { + pub fn get_pool() -> &'static ResponsePool { POOL.with(|p| *p) } #[inline] pub fn get_builder( - pool: &'static HttpResponsePool, status: StatusCode, - ) -> HttpResponseBuilder { + pool: &'static ResponsePool, status: StatusCode, + ) -> ResponseBuilder { if let Some(mut msg) = pool.0.borrow_mut().pop_front() { msg.status = status; - HttpResponseBuilder { + ResponseBuilder { pool, response: Some(msg), err: None, cookies: None, } } else { - let msg = Box::new(InnerHttpResponse::new(status, Body::Empty)); - HttpResponseBuilder { + let msg = Box::new(InnerResponse::new(status, Body::Empty)); + ResponseBuilder { pool, response: Some(msg), err: None, @@ -894,30 +894,30 @@ impl HttpResponsePool { #[inline] pub fn get_response( - pool: &'static HttpResponsePool, status: StatusCode, body: Body, - ) -> HttpResponse { + pool: &'static ResponsePool, status: StatusCode, body: Body, + ) -> Response { if let Some(mut msg) = pool.0.borrow_mut().pop_front() { msg.status = status; msg.body = body; - HttpResponse(msg, pool) + Response(msg, pool) } else { - let msg = Box::new(InnerHttpResponse::new(status, body)); - HttpResponse(msg, pool) + let msg = Box::new(InnerResponse::new(status, body)); + Response(msg, pool) } } #[inline] - fn get(status: StatusCode) -> HttpResponseBuilder { - POOL.with(|pool| HttpResponsePool::get_builder(pool, status)) + fn get(status: StatusCode) -> ResponseBuilder { + POOL.with(|pool| ResponsePool::get_builder(pool, status)) } #[inline] - fn with_body(status: StatusCode, body: Body) -> HttpResponse { - POOL.with(|pool| HttpResponsePool::get_response(pool, status, body)) + fn with_body(status: StatusCode, body: Body) -> Response { + POOL.with(|pool| ResponsePool::get_response(pool, status, body)) } #[inline] - fn release(&self, mut inner: Box) { + fn release(&self, mut inner: Box) { let mut p = self.0.borrow_mut(); if p.len() < 128 { inner.headers.clear(); @@ -946,12 +946,12 @@ mod tests { #[test] fn test_debug() { - let resp = HttpResponse::Ok() + let resp = Response::Ok() .header(COOKIE, HeaderValue::from_static("cookie1=value1; ")) .header(COOKIE, HeaderValue::from_static("cookie2=value2; ")) .finish(); let dbg = format!("{:?}", resp); - assert!(dbg.contains("HttpResponse")); + assert!(dbg.contains("Response")); } // #[test] @@ -962,7 +962,7 @@ mod tests { // .finish(); // let cookies = req.cookies().unwrap(); - // let resp = HttpResponse::Ok() + // let resp = Response::Ok() // .cookie( // http::Cookie::build("name", "value") // .domain("www.rust-lang.org") @@ -989,7 +989,7 @@ mod tests { #[test] fn test_update_response_cookies() { - let mut r = HttpResponse::Ok() + let mut r = Response::Ok() .cookie(http::Cookie::new("original", "val100")) .finish(); @@ -1012,7 +1012,7 @@ mod tests { #[test] fn test_basic_builder() { - let resp = HttpResponse::Ok() + let resp = Response::Ok() .header("X-TEST", "value") .version(Version::HTTP_10) .finish(); @@ -1022,19 +1022,19 @@ mod tests { #[test] fn test_upgrade() { - let resp = HttpResponse::build(StatusCode::OK).upgrade().finish(); + let resp = Response::build(StatusCode::OK).upgrade().finish(); assert!(resp.upgrade()) } #[test] fn test_force_close() { - let resp = HttpResponse::build(StatusCode::OK).force_close().finish(); + let resp = Response::build(StatusCode::OK).force_close().finish(); assert!(!resp.keep_alive().unwrap()) } #[test] fn test_content_type() { - let resp = HttpResponse::build(StatusCode::OK) + let resp = Response::build(StatusCode::OK) .content_type("text/plain") .body(Body::Empty); assert_eq!(resp.headers().get(CONTENT_TYPE).unwrap(), "text/plain") @@ -1042,18 +1042,18 @@ mod tests { #[test] fn test_content_encoding() { - let resp = HttpResponse::build(StatusCode::OK).finish(); + let resp = Response::build(StatusCode::OK).finish(); assert_eq!(resp.content_encoding(), None); #[cfg(feature = "brotli")] { - let resp = HttpResponse::build(StatusCode::OK) + let resp = Response::build(StatusCode::OK) .content_encoding(ContentEncoding::Br) .finish(); assert_eq!(resp.content_encoding(), Some(ContentEncoding::Br)); } - let resp = HttpResponse::build(StatusCode::OK) + let resp = Response::build(StatusCode::OK) .content_encoding(ContentEncoding::Gzip) .finish(); assert_eq!(resp.content_encoding(), Some(ContentEncoding::Gzip)); @@ -1061,7 +1061,7 @@ mod tests { #[test] fn test_json() { - let resp = HttpResponse::build(StatusCode::OK).json(vec!["v1", "v2", "v3"]); + let resp = Response::build(StatusCode::OK).json(vec!["v1", "v2", "v3"]); let ct = resp.headers().get(CONTENT_TYPE).unwrap(); assert_eq!(ct, HeaderValue::from_static("application/json")); assert_eq!( @@ -1072,7 +1072,7 @@ mod tests { #[test] fn test_json_ct() { - let resp = HttpResponse::build(StatusCode::OK) + let resp = Response::build(StatusCode::OK) .header(CONTENT_TYPE, "text/json") .json(vec!["v1", "v2", "v3"]); let ct = resp.headers().get(CONTENT_TYPE).unwrap(); @@ -1085,7 +1085,7 @@ mod tests { #[test] fn test_json2() { - let resp = HttpResponse::build(StatusCode::OK).json2(&vec!["v1", "v2", "v3"]); + let resp = Response::build(StatusCode::OK).json2(&vec!["v1", "v2", "v3"]); let ct = resp.headers().get(CONTENT_TYPE).unwrap(); assert_eq!(ct, HeaderValue::from_static("application/json")); assert_eq!( @@ -1096,7 +1096,7 @@ mod tests { #[test] fn test_json2_ct() { - let resp = HttpResponse::build(StatusCode::OK) + let resp = Response::build(StatusCode::OK) .header(CONTENT_TYPE, "text/json") .json2(&vec!["v1", "v2", "v3"]); let ct = resp.headers().get(CONTENT_TYPE).unwrap(); @@ -1120,7 +1120,7 @@ mod tests { fn test_into_response() { let req = TestRequest::default().finish(); - let resp: HttpResponse = "test".into(); + let resp: Response = "test".into(); assert_eq!(resp.status(), StatusCode::OK); assert_eq!( resp.headers().get(CONTENT_TYPE).unwrap(), @@ -1129,7 +1129,7 @@ mod tests { assert_eq!(resp.status(), StatusCode::OK); assert_eq!(resp.body().bin_ref(), &Binary::from("test")); - let resp: HttpResponse = b"test".as_ref().into(); + let resp: Response = b"test".as_ref().into(); assert_eq!(resp.status(), StatusCode::OK); assert_eq!( resp.headers().get(CONTENT_TYPE).unwrap(), @@ -1138,7 +1138,7 @@ mod tests { assert_eq!(resp.status(), StatusCode::OK); assert_eq!(resp.body().bin_ref(), &Binary::from(b"test".as_ref())); - let resp: HttpResponse = "test".to_owned().into(); + let resp: Response = "test".to_owned().into(); assert_eq!(resp.status(), StatusCode::OK); assert_eq!( resp.headers().get(CONTENT_TYPE).unwrap(), @@ -1147,7 +1147,7 @@ mod tests { assert_eq!(resp.status(), StatusCode::OK); assert_eq!(resp.body().bin_ref(), &Binary::from("test".to_owned())); - let resp: HttpResponse = (&"test".to_owned()).into(); + let resp: Response = (&"test".to_owned()).into(); assert_eq!(resp.status(), StatusCode::OK); assert_eq!( resp.headers().get(CONTENT_TYPE).unwrap(), @@ -1157,7 +1157,7 @@ mod tests { assert_eq!(resp.body().bin_ref(), &Binary::from(&"test".to_owned())); let b = Bytes::from_static(b"test"); - let resp: HttpResponse = b.into(); + let resp: Response = b.into(); assert_eq!(resp.status(), StatusCode::OK); assert_eq!( resp.headers().get(CONTENT_TYPE).unwrap(), @@ -1170,7 +1170,7 @@ mod tests { ); let b = Bytes::from_static(b"test"); - let resp: HttpResponse = b.into(); + let resp: Response = b.into(); assert_eq!(resp.status(), StatusCode::OK); assert_eq!( resp.headers().get(CONTENT_TYPE).unwrap(), @@ -1180,7 +1180,7 @@ mod tests { assert_eq!(resp.body().bin_ref(), &Binary::from(BytesMut::from("test"))); let b = BytesMut::from("test"); - let resp: HttpResponse = b.into(); + let resp: Response = b.into(); assert_eq!(resp.status(), StatusCode::OK); assert_eq!( resp.headers().get(CONTENT_TYPE).unwrap(), @@ -1192,7 +1192,7 @@ mod tests { #[test] fn test_into_builder() { - let mut resp: HttpResponse = "test".into(); + let mut resp: Response = "test".into(); assert_eq!(resp.status(), StatusCode::OK); resp.add_cookie(&http::Cookie::new("cookie1", "val100")) diff --git a/src/test.rs b/src/test.rs index 3c48df64..71145cee 100644 --- a/src/test.rs +++ b/src/test.rs @@ -25,12 +25,12 @@ use uri::Url as InnerUrl; /// /// # Examples /// -/// ```rust +/// ```rust,ignore /// # extern crate actix_web; /// # use actix_web::*; /// # -/// # fn my_handler(req: &HttpRequest) -> HttpResponse { -/// # HttpResponse::Ok().into() +/// # fn my_handler(req: &HttpRequest) -> Response { +/// # Response::Ok().into() /// # } /// # /// # fn main() { @@ -248,20 +248,20 @@ impl Drop for TestServer { // } // } -/// Test `HttpRequest` builder +/// Test `Request` builder /// -/// ```rust +/// ```rust,ignore /// # extern crate http; /// # extern crate actix_web; /// # use http::{header, StatusCode}; /// # use actix_web::*; /// use actix_web::test::TestRequest; /// -/// fn index(req: &HttpRequest) -> HttpResponse { +/// fn index(req: &HttpRequest) -> Response { /// if let Some(hdr) = req.headers().get(header::CONTENT_TYPE) { -/// HttpResponse::Ok().into() +/// Response::Ok().into() /// } else { -/// HttpResponse::BadRequest().into() +/// Response::BadRequest().into() /// } /// } /// @@ -403,7 +403,7 @@ impl TestRequest { // /// This method generates `HttpRequest` instance and runs handler // /// with generated request. - // pub fn run>(self, h: &H) -> Result { + // pub fn run>(self, h: &H) -> Result { // let req = self.finish(); // let resp = h.handle(&req); @@ -424,7 +424,7 @@ impl TestRequest { // /// with generated request. // /// // /// This method panics is handler returns actor. - // pub fn run_async(self, h: H) -> Result + // pub fn run_async(self, h: H) -> Result // where // H: Fn(HttpRequest) -> F + 'static, // F: Future + 'static, @@ -467,7 +467,7 @@ impl TestRequest { // } // /// This method generates `HttpRequest` instance and executes handler - // pub fn execute(self, f: F) -> Result + // pub fn execute(self, f: F) -> Result // where // F: FnOnce(&HttpRequest) -> R, // R: Responder + 'static, diff --git a/src/ws/mod.rs b/src/ws/mod.rs index 6bb84c18..61fad543 100644 --- a/src/ws/mod.rs +++ b/src/ws/mod.rs @@ -10,9 +10,9 @@ use http::{header, Method, StatusCode}; use body::Binary; use error::{PayloadError, ResponseError}; -use httpresponse::{ConnectionType, HttpResponse, HttpResponseBuilder}; use payload::PayloadBuffer; use request::Request; +use response::{ConnectionType, Response, ResponseBuilder}; mod frame; mod mask; @@ -85,26 +85,26 @@ pub enum HandshakeError { } impl ResponseError for HandshakeError { - fn error_response(&self) -> HttpResponse { + fn error_response(&self) -> Response { match *self { - HandshakeError::GetMethodRequired => HttpResponse::MethodNotAllowed() + HandshakeError::GetMethodRequired => Response::MethodNotAllowed() .header(header::ALLOW, "GET") .finish(), - HandshakeError::NoWebsocketUpgrade => HttpResponse::BadRequest() + HandshakeError::NoWebsocketUpgrade => Response::BadRequest() .reason("No WebSocket UPGRADE header found") .finish(), - HandshakeError::NoConnectionUpgrade => HttpResponse::BadRequest() + HandshakeError::NoConnectionUpgrade => Response::BadRequest() .reason("No CONNECTION upgrade") .finish(), - HandshakeError::NoVersionHeader => HttpResponse::BadRequest() + HandshakeError::NoVersionHeader => Response::BadRequest() .reason("Websocket version header is required") .finish(), - HandshakeError::UnsupportedVersion => HttpResponse::BadRequest() + HandshakeError::UnsupportedVersion => Response::BadRequest() .reason("Unsupported version") .finish(), - HandshakeError::BadWebsocketKey => HttpResponse::BadRequest() - .reason("Handshake error") - .finish(), + HandshakeError::BadWebsocketKey => { + Response::BadRequest().reason("Handshake error").finish() + } } } } @@ -126,13 +126,13 @@ pub enum Message { /// Prepare `WebSocket` handshake response. /// -/// This function returns handshake `HttpResponse`, ready to send to peer. +/// This function returns handshake `Response`, ready to send to peer. /// It does not perform any IO. /// // /// `protocols` is a sequence of known protocols. On successful handshake, // /// the returned response headers contain the first protocol in this list // /// which the server also knows. -pub fn handshake(req: &Request) -> Result { +pub fn handshake(req: &Request) -> Result { // WebSocket accepts only GET if *req.method() != Method::GET { return Err(HandshakeError::GetMethodRequired); @@ -181,7 +181,7 @@ pub fn handshake(req: &Request) -> Result { proto::hash_key(key.as_ref()) }; - Ok(HttpResponse::build(StatusCode::SWITCHING_PROTOCOLS) + Ok(Response::build(StatusCode::SWITCHING_PROTOCOLS) .connection_type(ConnectionType::Upgrade) .header(header::UPGRADE, "websocket") .header(header::TRANSFER_ENCODING, "chunked") @@ -280,20 +280,6 @@ where } } -/// Common writing methods for a websocket. -pub trait WsWriter { - /// Send a text - fn send_text>(&mut self, text: T); - /// Send a binary - fn send_binary>(&mut self, data: B); - /// Send a ping message - fn send_ping(&mut self, message: &str); - /// Send a pong message - fn send_pong(&mut self, message: &str); - /// Close the connection - fn send_close(&mut self, reason: Option); -} - #[cfg(test)] mod tests { use super::*; @@ -399,17 +385,17 @@ mod tests { #[test] fn test_wserror_http_response() { - let resp: HttpResponse = HandshakeError::GetMethodRequired.error_response(); + let resp: Response = HandshakeError::GetMethodRequired.error_response(); assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED); - let resp: HttpResponse = HandshakeError::NoWebsocketUpgrade.error_response(); + let resp: Response = HandshakeError::NoWebsocketUpgrade.error_response(); assert_eq!(resp.status(), StatusCode::BAD_REQUEST); - let resp: HttpResponse = HandshakeError::NoConnectionUpgrade.error_response(); + let resp: Response = HandshakeError::NoConnectionUpgrade.error_response(); assert_eq!(resp.status(), StatusCode::BAD_REQUEST); - let resp: HttpResponse = HandshakeError::NoVersionHeader.error_response(); + let resp: Response = HandshakeError::NoVersionHeader.error_response(); assert_eq!(resp.status(), StatusCode::BAD_REQUEST); - let resp: HttpResponse = HandshakeError::UnsupportedVersion.error_response(); + let resp: Response = HandshakeError::UnsupportedVersion.error_response(); assert_eq!(resp.status(), StatusCode::BAD_REQUEST); - let resp: HttpResponse = HandshakeError::BadWebsocketKey.error_response(); + let resp: Response = HandshakeError::BadWebsocketKey.error_response(); assert_eq!(resp.status(), StatusCode::BAD_REQUEST); } } diff --git a/tests/test_h1v2.rs b/tests/test_h1v2.rs index bb943065..1866f29b 100644 --- a/tests/test_h1v2.rs +++ b/tests/test_h1v2.rs @@ -11,7 +11,7 @@ use actix_net::server::Server; use actix_web::{client, test}; use futures::future; -use actix_http::{h1, Error, HttpResponse, KeepAlive, ServiceConfig}; +use actix_http::{h1, Error, KeepAlive, Response, ServiceConfig}; #[test] fn test_h1_v2() { @@ -29,7 +29,7 @@ fn test_h1_v2() { h1::H1Service::new(settings, |req| { println!("REQ: {:?}", req); - future::ok::<_, Error>(HttpResponse::Ok().finish()) + future::ok::<_, Error>(Response::Ok().finish()) }) }).unwrap() .run();