1
0
mirror of https://github.com/fafhrd91/actix-web synced 2024-11-24 08:22:59 +01:00

rename HttpResponse

This commit is contained in:
Nikolay Kim 2018-10-05 11:04:59 -07:00
parent d53f3d7187
commit 8c2244dd88
16 changed files with 266 additions and 287 deletions

View File

@ -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 Actix http

View File

@ -21,8 +21,7 @@ pub use url::ParseError as UrlParseError;
// re-exports // re-exports
pub use cookie::ParseError as CookieParseError; pub use cookie::ParseError as CookieParseError;
// use httprequest::HttpRequest; use response::{Response, ResponseParts};
use httpresponse::{HttpResponse, HttpResponseParts};
/// A specialized [`Result`](https://doc.rust-lang.org/std/result/enum.Result.html) /// A specialized [`Result`](https://doc.rust-lang.org/std/result/enum.Result.html)
/// for actix web operations /// for actix web operations
@ -124,13 +123,13 @@ impl<T: ResponseError> InternalResponseErrorAsFail for T {
} }
} }
/// Error that can be converted to `HttpResponse` /// Error that can be converted to `Response`
pub trait ResponseError: Fail + InternalResponseErrorAsFail { pub trait ResponseError: Fail + InternalResponseErrorAsFail {
/// Create response for error /// Create response for error
/// ///
/// Internal server error is generated by default. /// Internal server error is generated by default.
fn error_response(&self) -> HttpResponse { fn error_response(&self) -> Response {
HttpResponse::new(StatusCode::INTERNAL_SERVER_ERROR) Response::new(StatusCode::INTERNAL_SERVER_ERROR)
} }
} }
@ -155,10 +154,10 @@ impl fmt::Debug for Error {
} }
} }
/// Convert `Error` to a `HttpResponse` instance /// Convert `Error` to a `Response` instance
impl From<Error> for HttpResponse { impl From<Error> for Response {
fn from(err: Error) -> Self { 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` /// Return `BAD_REQUEST` for `de::value::Error`
impl ResponseError for DeError { impl ResponseError for DeError {
fn error_response(&self) -> HttpResponse { fn error_response(&self) -> Response {
HttpResponse::new(StatusCode::BAD_REQUEST) Response::new(StatusCode::BAD_REQUEST)
} }
} }
/// Return `BAD_REQUEST` for `Utf8Error` /// Return `BAD_REQUEST` for `Utf8Error`
impl ResponseError for Utf8Error { impl ResponseError for Utf8Error {
fn error_response(&self) -> HttpResponse { fn error_response(&self) -> Response {
HttpResponse::new(StatusCode::BAD_REQUEST) Response::new(StatusCode::BAD_REQUEST)
} }
} }
@ -220,26 +219,26 @@ impl ResponseError for HttpError {}
/// Return `InternalServerError` for `io::Error` /// Return `InternalServerError` for `io::Error`
impl ResponseError for io::Error { impl ResponseError for io::Error {
fn error_response(&self) -> HttpResponse { fn error_response(&self) -> Response {
match self.kind() { match self.kind() {
io::ErrorKind::NotFound => HttpResponse::new(StatusCode::NOT_FOUND), io::ErrorKind::NotFound => Response::new(StatusCode::NOT_FOUND),
io::ErrorKind::PermissionDenied => HttpResponse::new(StatusCode::FORBIDDEN), io::ErrorKind::PermissionDenied => Response::new(StatusCode::FORBIDDEN),
_ => HttpResponse::new(StatusCode::INTERNAL_SERVER_ERROR), _ => Response::new(StatusCode::INTERNAL_SERVER_ERROR),
} }
} }
} }
/// `BadRequest` for `InvalidHeaderValue` /// `BadRequest` for `InvalidHeaderValue`
impl ResponseError for header::InvalidHeaderValue { impl ResponseError for header::InvalidHeaderValue {
fn error_response(&self) -> HttpResponse { fn error_response(&self) -> Response {
HttpResponse::new(StatusCode::BAD_REQUEST) Response::new(StatusCode::BAD_REQUEST)
} }
} }
/// `BadRequest` for `InvalidHeaderValue` /// `BadRequest` for `InvalidHeaderValue`
impl ResponseError for header::InvalidHeaderValueBytes { impl ResponseError for header::InvalidHeaderValueBytes {
fn error_response(&self) -> HttpResponse { fn error_response(&self) -> Response {
HttpResponse::new(StatusCode::BAD_REQUEST) Response::new(StatusCode::BAD_REQUEST)
} }
} }
@ -288,8 +287,8 @@ pub enum ParseError {
/// Return `BadRequest` for `ParseError` /// Return `BadRequest` for `ParseError`
impl ResponseError for ParseError { impl ResponseError for ParseError {
fn error_response(&self) -> HttpResponse { fn error_response(&self) -> Response {
HttpResponse::new(StatusCode::BAD_REQUEST) Response::new(StatusCode::BAD_REQUEST)
} }
} }
@ -362,18 +361,18 @@ impl From<IoError> for PayloadError {
/// - `Overflow` returns `PayloadTooLarge` /// - `Overflow` returns `PayloadTooLarge`
/// - Other errors returns `BadRequest` /// - Other errors returns `BadRequest`
impl ResponseError for PayloadError { impl ResponseError for PayloadError {
fn error_response(&self) -> HttpResponse { fn error_response(&self) -> Response {
match *self { match *self {
PayloadError::Overflow => HttpResponse::new(StatusCode::PAYLOAD_TOO_LARGE), PayloadError::Overflow => Response::new(StatusCode::PAYLOAD_TOO_LARGE),
_ => HttpResponse::new(StatusCode::BAD_REQUEST), _ => Response::new(StatusCode::BAD_REQUEST),
} }
} }
} }
/// Return `BadRequest` for `cookie::ParseError` /// Return `BadRequest` for `cookie::ParseError`
impl ResponseError for cookie::ParseError { impl ResponseError for cookie::ParseError {
fn error_response(&self) -> HttpResponse { fn error_response(&self) -> Response {
HttpResponse::new(StatusCode::BAD_REQUEST) Response::new(StatusCode::BAD_REQUEST)
} }
} }
@ -443,8 +442,8 @@ pub enum ContentTypeError {
/// Return `BadRequest` for `ContentTypeError` /// Return `BadRequest` for `ContentTypeError`
impl ResponseError for ContentTypeError { impl ResponseError for ContentTypeError {
fn error_response(&self) -> HttpResponse { fn error_response(&self) -> Response {
HttpResponse::new(StatusCode::BAD_REQUEST) Response::new(StatusCode::BAD_REQUEST)
} }
} }
@ -475,15 +474,11 @@ pub enum UrlencodedError {
/// Return `BadRequest` for `UrlencodedError` /// Return `BadRequest` for `UrlencodedError`
impl ResponseError for UrlencodedError { impl ResponseError for UrlencodedError {
fn error_response(&self) -> HttpResponse { fn error_response(&self) -> Response {
match *self { match *self {
UrlencodedError::Overflow => { UrlencodedError::Overflow => Response::new(StatusCode::PAYLOAD_TOO_LARGE),
HttpResponse::new(StatusCode::PAYLOAD_TOO_LARGE) UrlencodedError::UnknownLength => Response::new(StatusCode::LENGTH_REQUIRED),
} _ => Response::new(StatusCode::BAD_REQUEST),
UrlencodedError::UnknownLength => {
HttpResponse::new(StatusCode::LENGTH_REQUIRED)
}
_ => HttpResponse::new(StatusCode::BAD_REQUEST),
} }
} }
} }
@ -513,12 +508,10 @@ pub enum JsonPayloadError {
/// Return `BadRequest` for `UrlencodedError` /// Return `BadRequest` for `UrlencodedError`
impl ResponseError for JsonPayloadError { impl ResponseError for JsonPayloadError {
fn error_response(&self) -> HttpResponse { fn error_response(&self) -> Response {
match *self { match *self {
JsonPayloadError::Overflow => { JsonPayloadError::Overflow => Response::new(StatusCode::PAYLOAD_TOO_LARGE),
HttpResponse::new(StatusCode::PAYLOAD_TOO_LARGE) _ => Response::new(StatusCode::BAD_REQUEST),
}
_ => HttpResponse::new(StatusCode::BAD_REQUEST),
} }
} }
} }
@ -606,7 +599,7 @@ pub struct InternalError<T> {
enum InternalErrorType { enum InternalErrorType {
Status(StatusCode), Status(StatusCode),
Response(Box<Mutex<Option<HttpResponseParts>>>), Response(Box<Mutex<Option<ResponseParts>>>),
} }
impl<T> InternalError<T> { impl<T> InternalError<T> {
@ -619,8 +612,8 @@ impl<T> InternalError<T> {
} }
} }
/// Create `InternalError` with predefined `HttpResponse`. /// Create `InternalError` with predefined `Response`.
pub fn from_response(cause: T, response: HttpResponse) -> Self { pub fn from_response(cause: T, response: Response) -> Self {
let resp = response.into_parts(); let resp = response.into_parts();
InternalError { InternalError {
cause, cause,
@ -661,14 +654,14 @@ impl<T> ResponseError for InternalError<T>
where where
T: Send + Sync + fmt::Debug + fmt::Display + 'static, T: Send + Sync + fmt::Debug + fmt::Display + 'static,
{ {
fn error_response(&self) -> HttpResponse { fn error_response(&self) -> Response {
match self.status { match self.status {
InternalErrorType::Status(st) => HttpResponse::new(st), InternalErrorType::Status(st) => Response::new(st),
InternalErrorType::Response(ref resp) => { InternalErrorType::Response(ref resp) => {
if let Some(resp) = resp.lock().unwrap().take() { if let Some(resp) = resp.lock().unwrap().take() {
HttpResponse::from_parts(resp) Response::from_parts(resp)
} else { } else {
HttpResponse::new(StatusCode::INTERNAL_SERVER_ERROR) Response::new(StatusCode::INTERNAL_SERVER_ERROR)
} }
} }
} }
@ -838,14 +831,14 @@ mod tests {
#[test] #[test]
fn test_into_response() { 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); 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); assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
let err: HttpError = StatusCode::from_u16(10000).err().unwrap().into(); 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); assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
} }
@ -883,7 +876,7 @@ mod tests {
fn test_error_http_response() { fn test_error_http_response() {
let orig = io::Error::new(io::ErrorKind::Other, "other"); let orig = io::Error::new(io::ErrorKind::Other, "other");
let e = Error::from(orig); let e = Error::from(orig);
let resp: HttpResponse = e.into(); let resp: Response = e.into();
assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR); assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
} }
@ -944,8 +937,8 @@ mod tests {
#[test] #[test]
fn test_internal_error() { fn test_internal_error() {
let err = let err =
InternalError::from_response(ParseError::Method, HttpResponse::Ok().into()); InternalError::from_response(ParseError::Method, Response::Ok().into());
let resp: HttpResponse = err.error_response(); let resp: Response = err.error_response();
assert_eq!(resp.status(), StatusCode::OK); assert_eq!(resp.status(), StatusCode::OK);
} }
@ -977,49 +970,49 @@ mod tests {
#[test] #[test]
fn test_error_helpers() { fn test_error_helpers() {
let r: HttpResponse = ErrorBadRequest("err").into(); let r: Response = ErrorBadRequest("err").into();
assert_eq!(r.status(), StatusCode::BAD_REQUEST); 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); assert_eq!(r.status(), StatusCode::UNAUTHORIZED);
let r: HttpResponse = ErrorForbidden("err").into(); let r: Response = ErrorForbidden("err").into();
assert_eq!(r.status(), StatusCode::FORBIDDEN); 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); 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); 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); 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); assert_eq!(r.status(), StatusCode::CONFLICT);
let r: HttpResponse = ErrorGone("err").into(); let r: Response = ErrorGone("err").into();
assert_eq!(r.status(), StatusCode::GONE); 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); 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); 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); 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); 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); 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); 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); assert_eq!(r.status(), StatusCode::GATEWAY_TIMEOUT);
} }
} }

View File

@ -12,8 +12,8 @@ use error::ParseError;
use helpers; use helpers;
use http::header::{HeaderValue, CONNECTION, CONTENT_LENGTH, DATE, TRANSFER_ENCODING}; use http::header::{HeaderValue, CONNECTION, CONTENT_LENGTH, DATE, TRANSFER_ENCODING};
use http::{Method, Version}; use http::{Method, Version};
use httpresponse::HttpResponse;
use request::RequestPool; use request::RequestPool;
use response::Response;
bitflags! { bitflags! {
struct Flags: u8 { struct Flags: u8 {
@ -29,7 +29,7 @@ const AVERAGE_HEADER_SIZE: usize = 30;
/// Http response /// Http response
pub enum OutMessage { pub enum OutMessage {
/// Http response message /// Http response message
Response(HttpResponse), Response(Response),
/// Payload chunk /// Payload chunk
Payload(Bytes), Payload(Bytes),
} }
@ -87,7 +87,7 @@ impl Codec {
} }
fn encode_response( fn encode_response(
&mut self, mut msg: HttpResponse, buffer: &mut BytesMut, &mut self, mut msg: Response, buffer: &mut BytesMut,
) -> io::Result<()> { ) -> io::Result<()> {
// prepare transfer encoding // prepare transfer encoding
self.te self.te

View File

@ -628,7 +628,7 @@ mod tests {
// let buf = Buffer::new("GET /test HTTP/1\r\n\r\n"); // let buf = Buffer::new("GET /test HTTP/1\r\n\r\n");
// let readbuf = BytesMut::new(); // 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.poll_io().is_ok()); // assert!(h1.poll_io().is_ok());
// assert!(h1.flags.contains(Flags::READ_DISCONNECTED)); // assert!(h1.flags.contains(Flags::READ_DISCONNECTED));

View File

@ -17,8 +17,8 @@ use body::Body;
use config::ServiceConfig; use config::ServiceConfig;
use error::DispatchError; use error::DispatchError;
use framed::Framed; use framed::Framed;
use httpresponse::HttpResponse;
use request::Request; use request::Request;
use response::Response;
use super::codec::{Codec, InMessage, OutMessage}; use super::codec::{Codec, InMessage, OutMessage};
@ -77,7 +77,7 @@ impl<S: Service> State<S> {
impl<T, S> Dispatcher<T, S> impl<T, S> Dispatcher<T, S>
where where
T: AsyncRead + AsyncWrite, T: AsyncRead + AsyncWrite,
S: Service<Request = Request, Response = HttpResponse>, S: Service<Request = Request, Response = Response>,
S::Error: Debug + Display, S::Error: Debug + Display,
{ {
/// Create http/1 dispatcher. /// Create http/1 dispatcher.
@ -415,7 +415,7 @@ where
.insert(Flags::STARTED | Flags::READ_DISCONNECTED); .insert(Flags::STARTED | Flags::READ_DISCONNECTED);
self.state = self.state =
State::SendResponse(Some(OutMessage::Response( State::SendResponse(Some(OutMessage::Response(
HttpResponse::RequestTimeout().finish(), Response::RequestTimeout().finish(),
))); )));
} else { } else {
trace!("Keep-alive timeout, close connection"); trace!("Keep-alive timeout, close connection");
@ -452,7 +452,7 @@ where
impl<T, S> Future for Dispatcher<T, S> impl<T, S> Future for Dispatcher<T, S>
where where
T: AsyncRead + AsyncWrite, T: AsyncRead + AsyncWrite,
S: Service<Request = Request, Response = HttpResponse>, S: Service<Request = Request, Response = Response>,
S::Error: Debug + Display, S::Error: Debug + Display,
{ {
type Item = (); type Item = ();

View File

@ -11,8 +11,8 @@ use http::{StatusCode, Version};
use body::{Binary, Body}; use body::{Binary, Body};
use header::ContentEncoding; use header::ContentEncoding;
use http::Method; use http::Method;
use httpresponse::HttpResponse;
use request::Request; use request::Request;
use response::Response;
#[derive(Debug)] #[derive(Debug)]
pub(crate) enum ResponseLength { pub(crate) enum ResponseLength {
@ -41,7 +41,7 @@ impl Default for ResponseEncoder {
} }
impl 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; self.head = head;
let version = resp.version().unwrap_or_else(|| version); let version = resp.version().unwrap_or_else(|| version);
@ -98,7 +98,7 @@ impl ResponseEncoder {
} }
fn streaming_encoding( fn streaming_encoding(
&mut self, version: Version, resp: &mut HttpResponse, &mut self, version: Version, resp: &mut Response,
) -> TransferEncoding { ) -> TransferEncoding {
match resp.chunked() { match resp.chunked() {
Some(true) => { Some(true) => {

View File

@ -7,8 +7,8 @@ use tokio_io::{AsyncRead, AsyncWrite};
use config::ServiceConfig; use config::ServiceConfig;
use error::DispatchError; use error::DispatchError;
use httpresponse::HttpResponse;
use request::Request; use request::Request;
use response::Response;
use super::dispatcher::Dispatcher; use super::dispatcher::Dispatcher;
@ -36,7 +36,7 @@ where
impl<T, S> NewService for H1Service<T, S> impl<T, S> NewService for H1Service<T, S>
where where
T: AsyncRead + AsyncWrite, T: AsyncRead + AsyncWrite,
S: NewService<Request = Request, Response = HttpResponse> + Clone, S: NewService<Request = Request, Response = Response> + Clone,
S::Service: Clone, S::Service: Clone,
S::Error: Debug + Display, S::Error: Debug + Display,
{ {
@ -65,7 +65,7 @@ pub struct H1ServiceResponse<T, S: NewService> {
impl<T, S> Future for H1ServiceResponse<T, S> impl<T, S> Future for H1ServiceResponse<T, S>
where where
T: AsyncRead + AsyncWrite, T: AsyncRead + AsyncWrite,
S: NewService<Request = Request, Response = HttpResponse>, S: NewService<Request = Request, Response = Response>,
S::Service: Clone, S::Service: Clone,
S::Error: Debug + Display, S::Error: Debug + Display,
{ {
@ -90,7 +90,7 @@ pub struct H1ServiceHandler<T, S> {
impl<T, S> H1ServiceHandler<T, S> impl<T, S> H1ServiceHandler<T, S>
where where
S: Service<Request = Request, Response = HttpResponse> + Clone, S: Service<Request = Request, Response = Response> + Clone,
S::Error: Debug + Display, S::Error: Debug + Display,
{ {
fn new(cfg: ServiceConfig, srv: S) -> H1ServiceHandler<T, S> { fn new(cfg: ServiceConfig, srv: S) -> H1ServiceHandler<T, S> {
@ -105,7 +105,7 @@ where
impl<T, S> Service for H1ServiceHandler<T, S> impl<T, S> Service for H1ServiceHandler<T, S>
where where
T: AsyncRead + AsyncWrite, T: AsyncRead + AsyncWrite,
S: Service<Request = Request, Response = HttpResponse> + Clone, S: Service<Request = Request, Response = Response> + Clone,
S::Error: Debug + Display, S::Error: Debug + Display,
{ {
type Request = T; type Request = T;

View File

@ -1,18 +1,18 @@
//! Basic http responses //! Basic http responses
#![allow(non_upper_case_globals)] #![allow(non_upper_case_globals)]
use http::StatusCode; use http::StatusCode;
use httpresponse::{HttpResponse, HttpResponseBuilder}; use response::{Response, ResponseBuilder};
macro_rules! STATIC_RESP { macro_rules! STATIC_RESP {
($name:ident, $status:expr) => { ($name:ident, $status:expr) => {
#[allow(non_snake_case, missing_docs)] #[allow(non_snake_case, missing_docs)]
pub fn $name() -> HttpResponseBuilder { pub fn $name() -> ResponseBuilder {
HttpResponse::build($status) Response::build($status)
} }
}; };
} }
impl HttpResponse { impl Response {
STATIC_RESP!(Ok, StatusCode::OK); STATIC_RESP!(Ok, StatusCode::OK);
STATIC_RESP!(Created, StatusCode::CREATED); STATIC_RESP!(Created, StatusCode::CREATED);
STATIC_RESP!(Accepted, StatusCode::ACCEPTED); STATIC_RESP!(Accepted, StatusCode::ACCEPTED);
@ -74,11 +74,11 @@ impl HttpResponse {
mod tests { mod tests {
use body::Body; use body::Body;
use http::StatusCode; use http::StatusCode;
use httpresponse::HttpResponse; use response::Response;
#[test] #[test]
fn test_build() { fn test_build() {
let resp = HttpResponse::Ok().body(Body::Empty); let resp = Response::Ok().body(Body::Empty);
assert_eq!(resp.status(), StatusCode::OK); assert_eq!(resp.status(), StatusCode::OK);
} }
} }

View File

@ -112,18 +112,18 @@ pub trait HttpMessage: Sized {
/// # extern crate futures; /// # extern crate futures;
/// # #[macro_use] extern crate serde_derive; /// # #[macro_use] extern crate serde_derive;
/// use actix_web::{ /// use actix_web::{
/// AsyncResponder, FutureResponse, HttpMessage, HttpRequest, HttpResponse, /// AsyncResponder, FutureResponse, HttpMessage, HttpRequest, Response,
/// }; /// };
/// use bytes::Bytes; /// use bytes::Bytes;
/// use futures::future::Future; /// use futures::future::Future;
/// ///
/// fn index(mut req: HttpRequest) -> FutureResponse<HttpResponse> { /// fn index(mut req: HttpRequest) -> FutureResponse<Response> {
/// req.body() // <- get Body future /// req.body() // <- get Body future
/// .limit(1024) // <- change max size of the body to a 1kb /// .limit(1024) // <- change max size of the body to a 1kb
/// .from_err() /// .from_err()
/// .and_then(|bytes: Bytes| { // <- complete body /// .and_then(|bytes: Bytes| { // <- complete body
/// println!("==== BODY ==== {:?}", bytes); /// println!("==== BODY ==== {:?}", bytes);
/// Ok(HttpResponse::Ok().into()) /// Ok(Response::Ok().into())
/// }).responder() /// }).responder()
/// } /// }
/// # fn main() {} /// # fn main() {}
@ -148,15 +148,15 @@ pub trait HttpMessage: Sized {
/// # extern crate futures; /// # extern crate futures;
/// # use futures::Future; /// # use futures::Future;
/// # use std::collections::HashMap; /// # use std::collections::HashMap;
/// use actix_web::{FutureResponse, HttpMessage, HttpRequest, HttpResponse}; /// use actix_web::{FutureResponse, HttpMessage, HttpRequest, Response};
/// ///
/// fn index(mut req: HttpRequest) -> FutureResponse<HttpResponse> { /// fn index(mut req: HttpRequest) -> FutureResponse<Response> {
/// Box::new( /// Box::new(
/// req.urlencoded::<HashMap<String, String>>() // <- get UrlEncoded future /// req.urlencoded::<HashMap<String, String>>() // <- get UrlEncoded future
/// .from_err() /// .from_err()
/// .and_then(|params| { // <- url encoded parameters /// .and_then(|params| { // <- url encoded parameters
/// println!("==== BODY ==== {:?}", params); /// println!("==== BODY ==== {:?}", params);
/// Ok(HttpResponse::Ok().into()) /// Ok(Response::Ok().into())
/// }), /// }),
/// ) /// )
/// } /// }
@ -188,12 +188,12 @@ pub trait HttpMessage: Sized {
/// name: String, /// name: String,
/// } /// }
/// ///
/// fn index(mut req: HttpRequest) -> Box<Future<Item = HttpResponse, Error = Error>> { /// fn index(mut req: HttpRequest) -> Box<Future<Item = Response, Error = Error>> {
/// req.json() // <- get JsonBody future /// req.json() // <- get JsonBody future
/// .from_err() /// .from_err()
/// .and_then(|val: MyObj| { // <- deserialized value /// .and_then(|val: MyObj| { // <- deserialized value
/// println!("==== BODY ==== {:?}", val); /// println!("==== BODY ==== {:?}", val);
/// Ok(HttpResponse::Ok().into()) /// Ok(Response::Ok().into())
/// }).responder() /// }).responder()
/// } /// }
/// # fn main() {} /// # fn main() {}

View File

@ -123,7 +123,7 @@ where
/// # extern crate actix_web; /// # extern crate actix_web;
/// # extern crate futures; /// # extern crate futures;
/// # #[macro_use] extern crate serde_derive; /// # #[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; /// use futures::future::Future;
/// ///
/// #[derive(Deserialize, Debug)] /// #[derive(Deserialize, Debug)]
@ -131,12 +131,12 @@ where
/// name: String, /// name: String,
/// } /// }
/// ///
/// fn index(mut req: HttpRequest) -> Box<Future<Item = HttpResponse, Error = Error>> { /// fn index(mut req: HttpRequest) -> Box<Future<Item = Response, Error = Error>> {
/// req.json() // <- get JsonBody future /// req.json() // <- get JsonBody future
/// .from_err() /// .from_err()
/// .and_then(|val: MyObj| { // <- deserialized value /// .and_then(|val: MyObj| { // <- deserialized value
/// println!("==== BODY ==== {:?}", val); /// println!("==== BODY ==== {:?}", val);
/// Ok(HttpResponse::Ok().into()) /// Ok(Response::Ok().into())
/// }).responder() /// }).responder()
/// } /// }
/// # fn main() {} /// # fn main() {}

View File

@ -41,8 +41,8 @@
//! represents an HTTP server instance and is used to instantiate and //! represents an HTTP server instance and is used to instantiate and
//! configure servers. //! configure servers.
//! //!
//! * [HttpRequest](struct.HttpRequest.html) and //! * [Request](struct.Request.html) and
//! [HttpResponse](struct.HttpResponse.html): These structs //! [Response](struct.Response.html): These structs
//! represent HTTP requests and responses and expose various methods //! represent HTTP requests and responses and expose various methods
//! for inspecting, creating and otherwise utilizing them. //! for inspecting, creating and otherwise utilizing them.
//! //!
@ -129,10 +129,10 @@ mod extensions;
mod header; mod header;
mod httpcodes; mod httpcodes;
mod httpmessage; mod httpmessage;
mod httpresponse;
mod json; mod json;
mod payload; mod payload;
mod request; mod request;
mod response;
mod uri; mod uri;
#[doc(hidden)] #[doc(hidden)]
@ -147,9 +147,9 @@ pub use body::{Binary, Body};
pub use error::{Error, ResponseError, Result}; pub use error::{Error, ResponseError, Result};
pub use extensions::Extensions; pub use extensions::Extensions;
pub use httpmessage::HttpMessage; pub use httpmessage::HttpMessage;
pub use httpresponse::HttpResponse;
pub use json::Json; pub use json::Json;
pub use request::Request; pub use request::Request;
pub use response::Response;
pub use self::config::{KeepAlive, ServiceConfig, ServiceConfigBuilder}; pub use self::config::{KeepAlive, ServiceConfig, ServiceConfigBuilder};
@ -166,9 +166,9 @@ pub mod dev {
pub use body::BodyStream; pub use body::BodyStream;
pub use httpmessage::{MessageBody, Readlines, UrlEncoded}; pub use httpmessage::{MessageBody, Readlines, UrlEncoded};
pub use httpresponse::HttpResponseBuilder;
pub use json::JsonBody; pub use json::JsonBody;
pub use payload::{Payload, PayloadBuffer}; pub use payload::{Payload, PayloadBuffer};
pub use response::ResponseBuilder;
} }
pub mod http { pub mod http {
@ -187,5 +187,5 @@ pub mod http {
pub use header::*; pub use header::*;
} }
pub use header::ContentEncoding; pub use header::ContentEncoding;
pub use httpresponse::ConnectionType; pub use response::ConnectionType;
} }

View File

@ -27,7 +27,7 @@ pub(crate) enum PayloadStatus {
/// `.readany()` method. Payload stream is not thread safe. Payload does not /// `.readany()` method. Payload stream is not thread safe. Payload does not
/// notify current task when new data is available. /// 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)] #[derive(Debug)]
pub struct Payload { pub struct Payload {
inner: Rc<RefCell<Inner>>, inner: Rc<RefCell<Inner>>,

View File

@ -31,54 +31,54 @@ pub enum ConnectionType {
} }
/// An HTTP Response /// An HTTP Response
pub struct HttpResponse(Box<InnerHttpResponse>, &'static HttpResponsePool); pub struct Response(Box<InnerResponse>, &'static ResponsePool);
impl HttpResponse { impl Response {
#[inline] #[inline]
fn get_ref(&self) -> &InnerHttpResponse { fn get_ref(&self) -> &InnerResponse {
self.0.as_ref() self.0.as_ref()
} }
#[inline] #[inline]
fn get_mut(&mut self) -> &mut InnerHttpResponse { fn get_mut(&mut self) -> &mut InnerResponse {
self.0.as_mut() self.0.as_mut()
} }
/// Create http response builder with specific status. /// Create http response builder with specific status.
#[inline] #[inline]
pub fn build(status: StatusCode) -> HttpResponseBuilder { pub fn build(status: StatusCode) -> ResponseBuilder {
HttpResponsePool::get(status) ResponsePool::get(status)
} }
/// Create http response builder /// Create http response builder
#[inline] #[inline]
pub fn build_from<T: Into<HttpResponseBuilder>>(source: T) -> HttpResponseBuilder { pub fn build_from<T: Into<ResponseBuilder>>(source: T) -> ResponseBuilder {
source.into() source.into()
} }
/// Constructs a response /// Constructs a response
#[inline] #[inline]
pub fn new(status: StatusCode) -> HttpResponse { pub fn new(status: StatusCode) -> Response {
HttpResponsePool::with_body(status, Body::Empty) ResponsePool::with_body(status, Body::Empty)
} }
/// Constructs a response with body /// Constructs a response with body
#[inline] #[inline]
pub fn with_body<B: Into<Body>>(status: StatusCode, body: B) -> HttpResponse { pub fn with_body<B: Into<Body>>(status: StatusCode, body: B) -> Response {
HttpResponsePool::with_body(status, body.into()) ResponsePool::with_body(status, body.into())
} }
/// Constructs an error response /// Constructs an error response
#[inline] #[inline]
pub fn from_error(error: Error) -> HttpResponse { pub fn from_error(error: Error) -> Response {
let mut resp = error.as_response_error().error_response(); let mut resp = error.as_response_error().error_response();
resp.get_mut().error = Some(error); resp.get_mut().error = Some(error);
resp resp
} }
/// Convert `HttpResponse` to a `HttpResponseBuilder` /// Convert `Response` to a `ResponseBuilder`
#[inline] #[inline]
pub fn into_builder(self) -> HttpResponseBuilder { pub fn into_builder(self) -> ResponseBuilder {
// If this response has cookies, load them into a jar // If this response has cookies, load them into a jar
let mut jar: Option<CookieJar> = None; let mut jar: Option<CookieJar> = None;
for c in self.cookies() { for c in self.cookies() {
@ -91,7 +91,7 @@ impl HttpResponse {
} }
} }
HttpResponseBuilder { ResponseBuilder {
pool: self.1, pool: self.1,
response: Some(self.0), response: Some(self.0),
err: None, err: None,
@ -282,23 +282,23 @@ impl HttpResponse {
self.1.release(self.0); self.1.release(self.0);
} }
pub(crate) fn into_parts(self) -> HttpResponseParts { pub(crate) fn into_parts(self) -> ResponseParts {
self.0.into_parts() self.0.into_parts()
} }
pub(crate) fn from_parts(parts: HttpResponseParts) -> HttpResponse { pub(crate) fn from_parts(parts: ResponseParts) -> Response {
HttpResponse( Response(
Box::new(InnerHttpResponse::from_parts(parts)), Box::new(InnerResponse::from_parts(parts)),
HttpResponsePool::get_pool(), ResponsePool::get_pool(),
) )
} }
} }
impl fmt::Debug for HttpResponse { impl fmt::Debug for Response {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let res = writeln!( let res = writeln!(
f, f,
"\nHttpResponse {:?} {}{}", "\nResponse {:?} {}{}",
self.get_ref().version, self.get_ref().version,
self.get_ref().status, self.get_ref().status,
self.get_ref().reason.unwrap_or("") self.get_ref().reason.unwrap_or("")
@ -332,16 +332,16 @@ impl<'a> Iterator for CookieIter<'a> {
/// An HTTP response builder /// 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. /// builder-like pattern.
pub struct HttpResponseBuilder { pub struct ResponseBuilder {
pool: &'static HttpResponsePool, pool: &'static ResponsePool,
response: Option<Box<InnerHttpResponse>>, response: Option<Box<InnerResponse>>,
err: Option<HttpError>, err: Option<HttpError>,
cookies: Option<CookieJar>, cookies: Option<CookieJar>,
} }
impl HttpResponseBuilder { impl ResponseBuilder {
/// Set HTTP status code of this response. /// Set HTTP status code of this response.
#[inline] #[inline]
pub fn status(&mut self, status: StatusCode) -> &mut Self { pub fn status(&mut self, status: StatusCode) -> &mut Self {
@ -366,10 +366,10 @@ impl HttpResponseBuilder {
/// ///
/// ```rust,ignore /// ```rust,ignore
/// # extern crate actix_web; /// # extern crate actix_web;
/// use actix_web::{http, HttpRequest, HttpResponse, Result}; /// use actix_web::{http, Request, Response, Result};
/// ///
/// fn index(req: HttpRequest) -> Result<HttpResponse> { /// fn index(req: HttpRequest) -> Result<Response> {
/// Ok(HttpResponse::Ok() /// Ok(Response::Ok()
/// .set(http::header::IfModifiedSince( /// .set(http::header::IfModifiedSince(
/// "Sun, 07 Nov 1994 08:48:37 GMT".parse()?, /// "Sun, 07 Nov 1994 08:48:37 GMT".parse()?,
/// )) /// ))
@ -394,10 +394,10 @@ impl HttpResponseBuilder {
/// ///
/// ```rust,ignore /// ```rust,ignore
/// # extern crate actix_web; /// # extern crate actix_web;
/// use actix_web::{http, HttpRequest, HttpResponse}; /// use actix_web::{http, Request, Response};
/// ///
/// fn index(req: HttpRequest) -> HttpResponse { /// fn index(req: HttpRequest) -> Response {
/// HttpResponse::Ok() /// Response::Ok()
/// .header("X-TEST", "value") /// .header("X-TEST", "value")
/// .header(http::header::CONTENT_TYPE, "application/json") /// .header(http::header::CONTENT_TYPE, "application/json")
/// .finish() /// .finish()
@ -516,10 +516,10 @@ impl HttpResponseBuilder {
/// ///
/// ```rust,ignore /// ```rust,ignore
/// # extern crate actix_web; /// # extern crate actix_web;
/// use actix_web::{http, HttpRequest, HttpResponse, Result}; /// use actix_web::{http, HttpRequest, Response, Result};
/// ///
/// fn index(req: HttpRequest) -> HttpResponse { /// fn index(req: HttpRequest) -> Response {
/// HttpResponse::Ok() /// Response::Ok()
/// .cookie( /// .cookie(
/// http::Cookie::build("name", "value") /// http::Cookie::build("name", "value")
/// .domain("www.rust-lang.org") /// .domain("www.rust-lang.org")
@ -546,10 +546,10 @@ impl HttpResponseBuilder {
/// ///
/// ```rust,ignore /// ```rust,ignore
/// # extern crate actix_web; /// # extern crate actix_web;
/// use actix_web::{http, HttpRequest, HttpResponse, Result}; /// use actix_web::{http, HttpRequest, Response, Result};
/// ///
/// fn index(req: &HttpRequest) -> HttpResponse { /// fn index(req: &HttpRequest) -> Response {
/// let mut builder = HttpResponse::Ok(); /// let mut builder = Response::Ok();
/// ///
/// if let Some(ref cookie) = req.cookie("name") { /// if let Some(ref cookie) = req.cookie("name") {
/// builder.del_cookie(cookie); /// builder.del_cookie(cookie);
@ -575,7 +575,7 @@ impl HttpResponseBuilder {
/// true. /// true.
pub fn if_true<F>(&mut self, value: bool, f: F) -> &mut Self pub fn if_true<F>(&mut self, value: bool, f: F) -> &mut Self
where where
F: FnOnce(&mut HttpResponseBuilder), F: FnOnce(&mut ResponseBuilder),
{ {
if value { if value {
f(self); f(self);
@ -587,7 +587,7 @@ impl HttpResponseBuilder {
/// Some. /// Some.
pub fn if_some<T, F>(&mut self, value: Option<T>, f: F) -> &mut Self pub fn if_some<T, F>(&mut self, value: Option<T>, f: F) -> &mut Self
where where
F: FnOnce(T, &mut HttpResponseBuilder), F: FnOnce(T, &mut ResponseBuilder),
{ {
if let Some(val) = value { if let Some(val) = value {
f(val, self); f(val, self);
@ -609,10 +609,10 @@ impl HttpResponseBuilder {
self self
} }
/// Set a body and generate `HttpResponse`. /// Set a body and generate `Response`.
/// ///
/// `HttpResponseBuilder` can not be used after this call. /// `ResponseBuilder` can not be used after this call.
pub fn body<B: Into<Body>>(&mut self, body: B) -> HttpResponse { pub fn body<B: Into<Body>>(&mut self, body: B) -> Response {
if let Some(e) = self.err.take() { if let Some(e) = self.err.take() {
return Error::from(e).into(); return Error::from(e).into();
} }
@ -626,14 +626,14 @@ impl HttpResponseBuilder {
} }
} }
response.body = body.into(); response.body = body.into();
HttpResponse(response, self.pool) Response(response, self.pool)
} }
#[inline] #[inline]
/// Set a streaming body and generate `HttpResponse`. /// Set a streaming body and generate `Response`.
/// ///
/// `HttpResponseBuilder` can not be used after this call. /// `ResponseBuilder` can not be used after this call.
pub fn streaming<S, E>(&mut self, stream: S) -> HttpResponse pub fn streaming<S, E>(&mut self, stream: S) -> Response
where where
S: Stream<Item = Bytes, Error = E> + 'static, S: Stream<Item = Bytes, Error = E> + 'static,
E: Into<Error>, E: Into<Error>,
@ -641,17 +641,17 @@ impl HttpResponseBuilder {
self.body(Body::Streaming(Box::new(stream.map_err(|e| e.into())))) 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. /// `ResponseBuilder` can not be used after this call.
pub fn json<T: Serialize>(&mut self, value: T) -> HttpResponse { pub fn json<T: Serialize>(&mut self, value: T) -> Response {
self.json2(&value) 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. /// `ResponseBuilder` can not be used after this call.
pub fn json2<T: Serialize>(&mut self, value: &T) -> HttpResponse { pub fn json2<T: Serialize>(&mut self, value: &T) -> Response {
match serde_json::to_string(value) { match serde_json::to_string(value) {
Ok(body) => { Ok(body) => {
let contains = if let Some(parts) = parts(&mut self.response, &self.err) let contains = if let Some(parts) = parts(&mut self.response, &self.err)
@ -671,16 +671,16 @@ impl HttpResponseBuilder {
} }
#[inline] #[inline]
/// Set an empty body and generate `HttpResponse` /// Set an empty body and generate `Response`
/// ///
/// `HttpResponseBuilder` can not be used after this call. /// `ResponseBuilder` can not be used after this call.
pub fn finish(&mut self) -> HttpResponse { pub fn finish(&mut self) -> Response {
self.body(Body::Empty) self.body(Body::Empty)
} }
/// This method construct new `HttpResponseBuilder` /// This method construct new `ResponseBuilder`
pub fn take(&mut self) -> HttpResponseBuilder { pub fn take(&mut self) -> ResponseBuilder {
HttpResponseBuilder { ResponseBuilder {
pool: self.pool, pool: self.pool,
response: self.response.take(), response: self.response.take(),
err: self.err.take(), err: self.err.take(),
@ -692,8 +692,8 @@ impl HttpResponseBuilder {
#[inline] #[inline]
#[cfg_attr(feature = "cargo-clippy", allow(clippy::borrowed_box))] #[cfg_attr(feature = "cargo-clippy", allow(clippy::borrowed_box))]
fn parts<'a>( fn parts<'a>(
parts: &'a mut Option<Box<InnerHttpResponse>>, err: &Option<HttpError>, parts: &'a mut Option<Box<InnerResponse>>, err: &Option<HttpError>,
) -> Option<&'a mut Box<InnerHttpResponse>> { ) -> Option<&'a mut Box<InnerResponse>> {
if err.is_some() { if err.is_some() {
return None; return None;
} }
@ -701,7 +701,7 @@ fn parts<'a>(
} }
/// Helper converters /// Helper converters
impl<I: Into<HttpResponse>, E: Into<Error>> From<Result<I, E>> for HttpResponse { impl<I: Into<Response>, E: Into<Error>> From<Result<I, E>> for Response {
fn from(res: Result<I, E>) -> Self { fn from(res: Result<I, E>) -> Self {
match res { match res {
Ok(val) => val.into(), Ok(val) => val.into(),
@ -710,62 +710,62 @@ impl<I: Into<HttpResponse>, E: Into<Error>> From<Result<I, E>> for HttpResponse
} }
} }
impl From<HttpResponseBuilder> for HttpResponse { impl From<ResponseBuilder> for Response {
fn from(mut builder: HttpResponseBuilder) -> Self { fn from(mut builder: ResponseBuilder) -> Self {
builder.finish() builder.finish()
} }
} }
impl From<&'static str> for HttpResponse { impl From<&'static str> for Response {
fn from(val: &'static str) -> Self { fn from(val: &'static str) -> Self {
HttpResponse::Ok() Response::Ok()
.content_type("text/plain; charset=utf-8") .content_type("text/plain; charset=utf-8")
.body(val) .body(val)
} }
} }
impl From<&'static [u8]> for HttpResponse { impl From<&'static [u8]> for Response {
fn from(val: &'static [u8]) -> Self { fn from(val: &'static [u8]) -> Self {
HttpResponse::Ok() Response::Ok()
.content_type("application/octet-stream") .content_type("application/octet-stream")
.body(val) .body(val)
} }
} }
impl From<String> for HttpResponse { impl From<String> for Response {
fn from(val: String) -> Self { fn from(val: String) -> Self {
HttpResponse::Ok() Response::Ok()
.content_type("text/plain; charset=utf-8") .content_type("text/plain; charset=utf-8")
.body(val) .body(val)
} }
} }
impl<'a> From<&'a String> for HttpResponse { impl<'a> From<&'a String> for Response {
fn from(val: &'a String) -> Self { fn from(val: &'a String) -> Self {
HttpResponse::build(StatusCode::OK) Response::build(StatusCode::OK)
.content_type("text/plain; charset=utf-8") .content_type("text/plain; charset=utf-8")
.body(val) .body(val)
} }
} }
impl From<Bytes> for HttpResponse { impl From<Bytes> for Response {
fn from(val: Bytes) -> Self { fn from(val: Bytes) -> Self {
HttpResponse::Ok() Response::Ok()
.content_type("application/octet-stream") .content_type("application/octet-stream")
.body(val) .body(val)
} }
} }
impl From<BytesMut> for HttpResponse { impl From<BytesMut> for Response {
fn from(val: BytesMut) -> Self { fn from(val: BytesMut) -> Self {
HttpResponse::Ok() Response::Ok()
.content_type("application/octet-stream") .content_type("application/octet-stream")
.body(val) .body(val)
} }
} }
#[derive(Debug)] #[derive(Debug)]
struct InnerHttpResponse { struct InnerResponse {
version: Option<Version>, version: Option<Version>,
headers: HeaderMap, headers: HeaderMap,
status: StatusCode, status: StatusCode,
@ -779,7 +779,7 @@ struct InnerHttpResponse {
error: Option<Error>, error: Option<Error>,
} }
pub(crate) struct HttpResponseParts { pub(crate) struct ResponseParts {
version: Option<Version>, version: Option<Version>,
headers: HeaderMap, headers: HeaderMap,
status: StatusCode, status: StatusCode,
@ -790,10 +790,10 @@ pub(crate) struct HttpResponseParts {
error: Option<Error>, error: Option<Error>,
} }
impl InnerHttpResponse { impl InnerResponse {
#[inline] #[inline]
fn new(status: StatusCode, body: Body) -> InnerHttpResponse { fn new(status: StatusCode, body: Body) -> InnerResponse {
InnerHttpResponse { InnerResponse {
status, status,
body, body,
version: None, version: None,
@ -809,7 +809,7 @@ impl InnerHttpResponse {
} }
/// This is for failure, we can not have Send + Sync on Streaming and Actor response /// 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) { let body = match mem::replace(&mut self.body, Body::Empty) {
Body::Empty => None, Body::Empty => None,
Body::Binary(mut bin) => Some(bin.take()), Body::Binary(mut bin) => Some(bin.take()),
@ -819,7 +819,7 @@ impl InnerHttpResponse {
} }
}; };
HttpResponseParts { ResponseParts {
body, body,
version: self.version, version: self.version,
headers: self.headers, 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 { let body = if let Some(ref body) = parts.body {
Body::Binary(body.clone().into()) Body::Binary(body.clone().into())
} else { } else {
Body::Empty Body::Empty
}; };
InnerHttpResponse { InnerResponse {
body, body,
status: parts.status, status: parts.status,
version: parts.version, version: parts.version,
@ -855,35 +855,35 @@ impl InnerHttpResponse {
} }
/// Internal use only! /// Internal use only!
pub(crate) struct HttpResponsePool(RefCell<VecDeque<Box<InnerHttpResponse>>>); pub(crate) struct ResponsePool(RefCell<VecDeque<Box<InnerResponse>>>);
thread_local!(static POOL: &'static HttpResponsePool = HttpResponsePool::pool()); thread_local!(static POOL: &'static ResponsePool = ResponsePool::pool());
impl HttpResponsePool { impl ResponsePool {
fn pool() -> &'static HttpResponsePool { fn pool() -> &'static ResponsePool {
let pool = HttpResponsePool(RefCell::new(VecDeque::with_capacity(128))); let pool = ResponsePool(RefCell::new(VecDeque::with_capacity(128)));
Box::leak(Box::new(pool)) Box::leak(Box::new(pool))
} }
pub fn get_pool() -> &'static HttpResponsePool { pub fn get_pool() -> &'static ResponsePool {
POOL.with(|p| *p) POOL.with(|p| *p)
} }
#[inline] #[inline]
pub fn get_builder( pub fn get_builder(
pool: &'static HttpResponsePool, status: StatusCode, pool: &'static ResponsePool, status: StatusCode,
) -> HttpResponseBuilder { ) -> ResponseBuilder {
if let Some(mut msg) = pool.0.borrow_mut().pop_front() { if let Some(mut msg) = pool.0.borrow_mut().pop_front() {
msg.status = status; msg.status = status;
HttpResponseBuilder { ResponseBuilder {
pool, pool,
response: Some(msg), response: Some(msg),
err: None, err: None,
cookies: None, cookies: None,
} }
} else { } else {
let msg = Box::new(InnerHttpResponse::new(status, Body::Empty)); let msg = Box::new(InnerResponse::new(status, Body::Empty));
HttpResponseBuilder { ResponseBuilder {
pool, pool,
response: Some(msg), response: Some(msg),
err: None, err: None,
@ -894,30 +894,30 @@ impl HttpResponsePool {
#[inline] #[inline]
pub fn get_response( pub fn get_response(
pool: &'static HttpResponsePool, status: StatusCode, body: Body, pool: &'static ResponsePool, status: StatusCode, body: Body,
) -> HttpResponse { ) -> Response {
if let Some(mut msg) = pool.0.borrow_mut().pop_front() { if let Some(mut msg) = pool.0.borrow_mut().pop_front() {
msg.status = status; msg.status = status;
msg.body = body; msg.body = body;
HttpResponse(msg, pool) Response(msg, pool)
} else { } else {
let msg = Box::new(InnerHttpResponse::new(status, body)); let msg = Box::new(InnerResponse::new(status, body));
HttpResponse(msg, pool) Response(msg, pool)
} }
} }
#[inline] #[inline]
fn get(status: StatusCode) -> HttpResponseBuilder { fn get(status: StatusCode) -> ResponseBuilder {
POOL.with(|pool| HttpResponsePool::get_builder(pool, status)) POOL.with(|pool| ResponsePool::get_builder(pool, status))
} }
#[inline] #[inline]
fn with_body(status: StatusCode, body: Body) -> HttpResponse { fn with_body(status: StatusCode, body: Body) -> Response {
POOL.with(|pool| HttpResponsePool::get_response(pool, status, body)) POOL.with(|pool| ResponsePool::get_response(pool, status, body))
} }
#[inline] #[inline]
fn release(&self, mut inner: Box<InnerHttpResponse>) { fn release(&self, mut inner: Box<InnerResponse>) {
let mut p = self.0.borrow_mut(); let mut p = self.0.borrow_mut();
if p.len() < 128 { if p.len() < 128 {
inner.headers.clear(); inner.headers.clear();
@ -946,12 +946,12 @@ mod tests {
#[test] #[test]
fn test_debug() { fn test_debug() {
let resp = HttpResponse::Ok() let resp = Response::Ok()
.header(COOKIE, HeaderValue::from_static("cookie1=value1; ")) .header(COOKIE, HeaderValue::from_static("cookie1=value1; "))
.header(COOKIE, HeaderValue::from_static("cookie2=value2; ")) .header(COOKIE, HeaderValue::from_static("cookie2=value2; "))
.finish(); .finish();
let dbg = format!("{:?}", resp); let dbg = format!("{:?}", resp);
assert!(dbg.contains("HttpResponse")); assert!(dbg.contains("Response"));
} }
// #[test] // #[test]
@ -962,7 +962,7 @@ mod tests {
// .finish(); // .finish();
// let cookies = req.cookies().unwrap(); // let cookies = req.cookies().unwrap();
// let resp = HttpResponse::Ok() // let resp = Response::Ok()
// .cookie( // .cookie(
// http::Cookie::build("name", "value") // http::Cookie::build("name", "value")
// .domain("www.rust-lang.org") // .domain("www.rust-lang.org")
@ -989,7 +989,7 @@ mod tests {
#[test] #[test]
fn test_update_response_cookies() { fn test_update_response_cookies() {
let mut r = HttpResponse::Ok() let mut r = Response::Ok()
.cookie(http::Cookie::new("original", "val100")) .cookie(http::Cookie::new("original", "val100"))
.finish(); .finish();
@ -1012,7 +1012,7 @@ mod tests {
#[test] #[test]
fn test_basic_builder() { fn test_basic_builder() {
let resp = HttpResponse::Ok() let resp = Response::Ok()
.header("X-TEST", "value") .header("X-TEST", "value")
.version(Version::HTTP_10) .version(Version::HTTP_10)
.finish(); .finish();
@ -1022,19 +1022,19 @@ mod tests {
#[test] #[test]
fn test_upgrade() { fn test_upgrade() {
let resp = HttpResponse::build(StatusCode::OK).upgrade().finish(); let resp = Response::build(StatusCode::OK).upgrade().finish();
assert!(resp.upgrade()) assert!(resp.upgrade())
} }
#[test] #[test]
fn test_force_close() { 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()) assert!(!resp.keep_alive().unwrap())
} }
#[test] #[test]
fn test_content_type() { fn test_content_type() {
let resp = HttpResponse::build(StatusCode::OK) let resp = Response::build(StatusCode::OK)
.content_type("text/plain") .content_type("text/plain")
.body(Body::Empty); .body(Body::Empty);
assert_eq!(resp.headers().get(CONTENT_TYPE).unwrap(), "text/plain") assert_eq!(resp.headers().get(CONTENT_TYPE).unwrap(), "text/plain")
@ -1042,18 +1042,18 @@ mod tests {
#[test] #[test]
fn test_content_encoding() { fn test_content_encoding() {
let resp = HttpResponse::build(StatusCode::OK).finish(); let resp = Response::build(StatusCode::OK).finish();
assert_eq!(resp.content_encoding(), None); assert_eq!(resp.content_encoding(), None);
#[cfg(feature = "brotli")] #[cfg(feature = "brotli")]
{ {
let resp = HttpResponse::build(StatusCode::OK) let resp = Response::build(StatusCode::OK)
.content_encoding(ContentEncoding::Br) .content_encoding(ContentEncoding::Br)
.finish(); .finish();
assert_eq!(resp.content_encoding(), Some(ContentEncoding::Br)); assert_eq!(resp.content_encoding(), Some(ContentEncoding::Br));
} }
let resp = HttpResponse::build(StatusCode::OK) let resp = Response::build(StatusCode::OK)
.content_encoding(ContentEncoding::Gzip) .content_encoding(ContentEncoding::Gzip)
.finish(); .finish();
assert_eq!(resp.content_encoding(), Some(ContentEncoding::Gzip)); assert_eq!(resp.content_encoding(), Some(ContentEncoding::Gzip));
@ -1061,7 +1061,7 @@ mod tests {
#[test] #[test]
fn test_json() { 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(); let ct = resp.headers().get(CONTENT_TYPE).unwrap();
assert_eq!(ct, HeaderValue::from_static("application/json")); assert_eq!(ct, HeaderValue::from_static("application/json"));
assert_eq!( assert_eq!(
@ -1072,7 +1072,7 @@ mod tests {
#[test] #[test]
fn test_json_ct() { fn test_json_ct() {
let resp = HttpResponse::build(StatusCode::OK) let resp = Response::build(StatusCode::OK)
.header(CONTENT_TYPE, "text/json") .header(CONTENT_TYPE, "text/json")
.json(vec!["v1", "v2", "v3"]); .json(vec!["v1", "v2", "v3"]);
let ct = resp.headers().get(CONTENT_TYPE).unwrap(); let ct = resp.headers().get(CONTENT_TYPE).unwrap();
@ -1085,7 +1085,7 @@ mod tests {
#[test] #[test]
fn test_json2() { 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(); let ct = resp.headers().get(CONTENT_TYPE).unwrap();
assert_eq!(ct, HeaderValue::from_static("application/json")); assert_eq!(ct, HeaderValue::from_static("application/json"));
assert_eq!( assert_eq!(
@ -1096,7 +1096,7 @@ mod tests {
#[test] #[test]
fn test_json2_ct() { fn test_json2_ct() {
let resp = HttpResponse::build(StatusCode::OK) let resp = Response::build(StatusCode::OK)
.header(CONTENT_TYPE, "text/json") .header(CONTENT_TYPE, "text/json")
.json2(&vec!["v1", "v2", "v3"]); .json2(&vec!["v1", "v2", "v3"]);
let ct = resp.headers().get(CONTENT_TYPE).unwrap(); let ct = resp.headers().get(CONTENT_TYPE).unwrap();
@ -1120,7 +1120,7 @@ mod tests {
fn test_into_response() { fn test_into_response() {
let req = TestRequest::default().finish(); let req = TestRequest::default().finish();
let resp: HttpResponse = "test".into(); let resp: Response = "test".into();
assert_eq!(resp.status(), StatusCode::OK); assert_eq!(resp.status(), StatusCode::OK);
assert_eq!( assert_eq!(
resp.headers().get(CONTENT_TYPE).unwrap(), resp.headers().get(CONTENT_TYPE).unwrap(),
@ -1129,7 +1129,7 @@ mod tests {
assert_eq!(resp.status(), StatusCode::OK); assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(resp.body().bin_ref(), &Binary::from("test")); 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.status(), StatusCode::OK);
assert_eq!( assert_eq!(
resp.headers().get(CONTENT_TYPE).unwrap(), resp.headers().get(CONTENT_TYPE).unwrap(),
@ -1138,7 +1138,7 @@ mod tests {
assert_eq!(resp.status(), StatusCode::OK); assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(resp.body().bin_ref(), &Binary::from(b"test".as_ref())); 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.status(), StatusCode::OK);
assert_eq!( assert_eq!(
resp.headers().get(CONTENT_TYPE).unwrap(), resp.headers().get(CONTENT_TYPE).unwrap(),
@ -1147,7 +1147,7 @@ mod tests {
assert_eq!(resp.status(), StatusCode::OK); assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(resp.body().bin_ref(), &Binary::from("test".to_owned())); 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.status(), StatusCode::OK);
assert_eq!( assert_eq!(
resp.headers().get(CONTENT_TYPE).unwrap(), resp.headers().get(CONTENT_TYPE).unwrap(),
@ -1157,7 +1157,7 @@ mod tests {
assert_eq!(resp.body().bin_ref(), &Binary::from(&"test".to_owned())); assert_eq!(resp.body().bin_ref(), &Binary::from(&"test".to_owned()));
let b = Bytes::from_static(b"test"); 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.status(), StatusCode::OK);
assert_eq!( assert_eq!(
resp.headers().get(CONTENT_TYPE).unwrap(), resp.headers().get(CONTENT_TYPE).unwrap(),
@ -1170,7 +1170,7 @@ mod tests {
); );
let b = Bytes::from_static(b"test"); 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.status(), StatusCode::OK);
assert_eq!( assert_eq!(
resp.headers().get(CONTENT_TYPE).unwrap(), resp.headers().get(CONTENT_TYPE).unwrap(),
@ -1180,7 +1180,7 @@ mod tests {
assert_eq!(resp.body().bin_ref(), &Binary::from(BytesMut::from("test"))); assert_eq!(resp.body().bin_ref(), &Binary::from(BytesMut::from("test")));
let b = 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.status(), StatusCode::OK);
assert_eq!( assert_eq!(
resp.headers().get(CONTENT_TYPE).unwrap(), resp.headers().get(CONTENT_TYPE).unwrap(),
@ -1192,7 +1192,7 @@ mod tests {
#[test] #[test]
fn test_into_builder() { fn test_into_builder() {
let mut resp: HttpResponse = "test".into(); let mut resp: Response = "test".into();
assert_eq!(resp.status(), StatusCode::OK); assert_eq!(resp.status(), StatusCode::OK);
resp.add_cookie(&http::Cookie::new("cookie1", "val100")) resp.add_cookie(&http::Cookie::new("cookie1", "val100"))

View File

@ -25,12 +25,12 @@ use uri::Url as InnerUrl;
/// ///
/// # Examples /// # Examples
/// ///
/// ```rust /// ```rust,ignore
/// # extern crate actix_web; /// # extern crate actix_web;
/// # use actix_web::*; /// # use actix_web::*;
/// # /// #
/// # fn my_handler(req: &HttpRequest) -> HttpResponse { /// # fn my_handler(req: &HttpRequest) -> Response {
/// # HttpResponse::Ok().into() /// # Response::Ok().into()
/// # } /// # }
/// # /// #
/// # fn main() { /// # fn main() {
@ -248,20 +248,20 @@ impl Drop for TestServer {
// } // }
// } // }
/// Test `HttpRequest` builder /// Test `Request` builder
/// ///
/// ```rust /// ```rust,ignore
/// # extern crate http; /// # extern crate http;
/// # extern crate actix_web; /// # extern crate actix_web;
/// # use http::{header, StatusCode}; /// # use http::{header, StatusCode};
/// # use actix_web::*; /// # use actix_web::*;
/// use actix_web::test::TestRequest; /// 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) { /// if let Some(hdr) = req.headers().get(header::CONTENT_TYPE) {
/// HttpResponse::Ok().into() /// Response::Ok().into()
/// } else { /// } else {
/// HttpResponse::BadRequest().into() /// Response::BadRequest().into()
/// } /// }
/// } /// }
/// ///
@ -403,7 +403,7 @@ impl TestRequest {
// /// This method generates `HttpRequest` instance and runs handler // /// This method generates `HttpRequest` instance and runs handler
// /// with generated request. // /// with generated request.
// pub fn run<H: Handler<S>>(self, h: &H) -> Result<HttpResponse, Error> { // pub fn run<H: Handler<S>>(self, h: &H) -> Result<Response, Error> {
// let req = self.finish(); // let req = self.finish();
// let resp = h.handle(&req); // let resp = h.handle(&req);
@ -424,7 +424,7 @@ impl TestRequest {
// /// with generated request. // /// with generated request.
// /// // ///
// /// This method panics is handler returns actor. // /// This method panics is handler returns actor.
// pub fn run_async<H, R, F, E>(self, h: H) -> Result<HttpResponse, E> // pub fn run_async<H, R, F, E>(self, h: H) -> Result<Response, E>
// where // where
// H: Fn(HttpRequest<S>) -> F + 'static, // H: Fn(HttpRequest<S>) -> F + 'static,
// F: Future<Item = R, Error = E> + 'static, // F: Future<Item = R, Error = E> + 'static,
@ -467,7 +467,7 @@ impl TestRequest {
// } // }
// /// This method generates `HttpRequest` instance and executes handler // /// This method generates `HttpRequest` instance and executes handler
// pub fn execute<F, R>(self, f: F) -> Result<HttpResponse, Error> // pub fn execute<F, R>(self, f: F) -> Result<Response, Error>
// where // where
// F: FnOnce(&HttpRequest<S>) -> R, // F: FnOnce(&HttpRequest<S>) -> R,
// R: Responder + 'static, // R: Responder + 'static,

View File

@ -10,9 +10,9 @@ use http::{header, Method, StatusCode};
use body::Binary; use body::Binary;
use error::{PayloadError, ResponseError}; use error::{PayloadError, ResponseError};
use httpresponse::{ConnectionType, HttpResponse, HttpResponseBuilder};
use payload::PayloadBuffer; use payload::PayloadBuffer;
use request::Request; use request::Request;
use response::{ConnectionType, Response, ResponseBuilder};
mod frame; mod frame;
mod mask; mod mask;
@ -85,26 +85,26 @@ pub enum HandshakeError {
} }
impl ResponseError for HandshakeError { impl ResponseError for HandshakeError {
fn error_response(&self) -> HttpResponse { fn error_response(&self) -> Response {
match *self { match *self {
HandshakeError::GetMethodRequired => HttpResponse::MethodNotAllowed() HandshakeError::GetMethodRequired => Response::MethodNotAllowed()
.header(header::ALLOW, "GET") .header(header::ALLOW, "GET")
.finish(), .finish(),
HandshakeError::NoWebsocketUpgrade => HttpResponse::BadRequest() HandshakeError::NoWebsocketUpgrade => Response::BadRequest()
.reason("No WebSocket UPGRADE header found") .reason("No WebSocket UPGRADE header found")
.finish(), .finish(),
HandshakeError::NoConnectionUpgrade => HttpResponse::BadRequest() HandshakeError::NoConnectionUpgrade => Response::BadRequest()
.reason("No CONNECTION upgrade") .reason("No CONNECTION upgrade")
.finish(), .finish(),
HandshakeError::NoVersionHeader => HttpResponse::BadRequest() HandshakeError::NoVersionHeader => Response::BadRequest()
.reason("Websocket version header is required") .reason("Websocket version header is required")
.finish(), .finish(),
HandshakeError::UnsupportedVersion => HttpResponse::BadRequest() HandshakeError::UnsupportedVersion => Response::BadRequest()
.reason("Unsupported version") .reason("Unsupported version")
.finish(), .finish(),
HandshakeError::BadWebsocketKey => HttpResponse::BadRequest() HandshakeError::BadWebsocketKey => {
.reason("Handshake error") Response::BadRequest().reason("Handshake error").finish()
.finish(), }
} }
} }
} }
@ -126,13 +126,13 @@ pub enum Message {
/// Prepare `WebSocket` handshake response. /// 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. /// It does not perform any IO.
/// ///
// /// `protocols` is a sequence of known protocols. On successful handshake, // /// `protocols` is a sequence of known protocols. On successful handshake,
// /// the returned response headers contain the first protocol in this list // /// the returned response headers contain the first protocol in this list
// /// which the server also knows. // /// which the server also knows.
pub fn handshake(req: &Request) -> Result<HttpResponseBuilder, HandshakeError> { pub fn handshake(req: &Request) -> Result<ResponseBuilder, HandshakeError> {
// WebSocket accepts only GET // WebSocket accepts only GET
if *req.method() != Method::GET { if *req.method() != Method::GET {
return Err(HandshakeError::GetMethodRequired); return Err(HandshakeError::GetMethodRequired);
@ -181,7 +181,7 @@ pub fn handshake(req: &Request) -> Result<HttpResponseBuilder, HandshakeError> {
proto::hash_key(key.as_ref()) proto::hash_key(key.as_ref())
}; };
Ok(HttpResponse::build(StatusCode::SWITCHING_PROTOCOLS) Ok(Response::build(StatusCode::SWITCHING_PROTOCOLS)
.connection_type(ConnectionType::Upgrade) .connection_type(ConnectionType::Upgrade)
.header(header::UPGRADE, "websocket") .header(header::UPGRADE, "websocket")
.header(header::TRANSFER_ENCODING, "chunked") .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<T: Into<Binary>>(&mut self, text: T);
/// Send a binary
fn send_binary<B: Into<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<CloseReason>);
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
@ -399,17 +385,17 @@ mod tests {
#[test] #[test]
fn test_wserror_http_response() { 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); 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); 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); 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); 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); 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); assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
} }
} }

View File

@ -11,7 +11,7 @@ use actix_net::server::Server;
use actix_web::{client, test}; use actix_web::{client, test};
use futures::future; use futures::future;
use actix_http::{h1, Error, HttpResponse, KeepAlive, ServiceConfig}; use actix_http::{h1, Error, KeepAlive, Response, ServiceConfig};
#[test] #[test]
fn test_h1_v2() { fn test_h1_v2() {
@ -29,7 +29,7 @@ fn test_h1_v2() {
h1::H1Service::new(settings, |req| { h1::H1Service::new(settings, |req| {
println!("REQ: {:?}", req); println!("REQ: {:?}", req);
future::ok::<_, Error>(HttpResponse::Ok().finish()) future::ok::<_, Error>(Response::Ok().finish())
}) })
}).unwrap() }).unwrap()
.run(); .run();