1
0
mirror of https://github.com/fafhrd91/actix-web synced 2025-06-24 22:37:35 +02:00

remove http-codes builders from actix-http (#2159)

This commit is contained in:
Rob Ede
2021-04-14 02:00:14 +01:00
committed by GitHub
parent 02ced426fd
commit 23e0c9b6e0
21 changed files with 539 additions and 573 deletions

View File

@ -3,6 +3,7 @@
## Unreleased - 2021-xx-xx
### Added
* `impl<T: MessageBody> MessageBody for Pin<Box<T>>`. [#2152]
* `Response::{ok, bad_request, not_found, internal_server_error}`. [#2159]
* Helper `body::to_bytes` for async collecting message body into Bytes. [#2158]
### Changes
@ -19,10 +20,13 @@
* `ResponseBuilder::json`. [#2148]
* `ResponseBuilder::{set_header, header}`. [#2148]
* `impl From<serde_json::Value> for Body`. [#2148]
* `Response::build_from`. [#2159]
* Most of the status code builders on `Response`. [#2159]
[#2065]: https://github.com/actix/actix-web/pull/2065
[#2148]: https://github.com/actix/actix-web/pull/2148
[#2152]: https://github.com/actix/actix-web/pull/2152
[#2159]: https://github.com/actix/actix-web/pull/2159
[#2158]: https://github.com/actix/actix-web/pull/2158

View File

@ -1,6 +1,6 @@
use std::{env, io};
use actix_http::{Error, HttpService, Request, Response};
use actix_http::{http::StatusCode, Error, HttpService, Request, Response};
use actix_server::Server;
use bytes::BytesMut;
use futures_util::StreamExt as _;
@ -25,7 +25,7 @@ async fn main() -> io::Result<()> {
info!("request body: {:?}", body);
Ok::<_, Error>(
Response::Ok()
Response::build(StatusCode::OK)
.insert_header((
"x-head",
HeaderValue::from_static("dummy value!"),

View File

@ -1,6 +1,6 @@
use std::{env, io};
use actix_http::{body::Body, http::HeaderValue};
use actix_http::{body::Body, http::HeaderValue, http::StatusCode};
use actix_http::{Error, HttpService, Request, Response};
use actix_server::Server;
use bytes::BytesMut;
@ -14,7 +14,7 @@ async fn handle_request(mut req: Request) -> Result<Response<Body>, Error> {
}
info!("request body: {:?}", body);
Ok(Response::Ok()
Ok(Response::build(StatusCode::OK)
.insert_header(("x-head", HeaderValue::from_static("dummy value!")))
.body(body))
}

View File

@ -1,6 +1,6 @@
use std::{env, io};
use actix_http::{HttpService, Response};
use actix_http::{http::StatusCode, HttpService, Response};
use actix_server::Server;
use actix_utils::future;
use http::header::HeaderValue;
@ -18,7 +18,7 @@ async fn main() -> io::Result<()> {
.client_disconnect(1000)
.finish(|_req| {
info!("{:?}", _req);
let mut res = Response::Ok();
let mut res = Response::build(StatusCode::OK);
res.insert_header((
"x-head",
HeaderValue::from_static("dummy value!"),

View File

@ -1021,8 +1021,7 @@ mod tests {
#[test]
fn test_internal_error() {
let err =
InternalError::from_response(ParseError::Method, Response::Ok().into());
let err = InternalError::from_response(ParseError::Method, Response::ok());
let resp: Response<Body> = err.error_response();
assert_eq!(resp.status(), StatusCode::OK);
}

View File

@ -21,6 +21,7 @@ use crate::body::{Body, BodySize, MessageBody, ResponseBody};
use crate::config::ServiceConfig;
use crate::error::{DispatchError, Error};
use crate::error::{ParseError, PayloadError};
use crate::http::StatusCode;
use crate::request::Request;
use crate::response::Response;
use crate::service::HttpFlow;
@ -562,7 +563,7 @@ where
);
this.flags.insert(Flags::READ_DISCONNECT);
this.messages.push_back(DispatcherMessage::Error(
Response::InternalServerError().finish().drop_body(),
Response::internal_server_error().drop_body(),
));
*this.error = Some(DispatchError::InternalError);
break;
@ -575,7 +576,7 @@ where
error!("Internal server error: unexpected eof");
this.flags.insert(Flags::READ_DISCONNECT);
this.messages.push_back(DispatcherMessage::Error(
Response::InternalServerError().finish().drop_body(),
Response::internal_server_error().drop_body(),
));
*this.error = Some(DispatchError::InternalError);
break;
@ -598,7 +599,8 @@ where
}
// Requests overflow buffer size should be responded with 431
this.messages.push_back(DispatcherMessage::Error(
Response::RequestHeaderFieldsTooLarge().finish().drop_body(),
Response::new(StatusCode::REQUEST_HEADER_FIELDS_TOO_LARGE)
.drop_body(),
));
this.flags.insert(Flags::READ_DISCONNECT);
*this.error = Some(ParseError::TooLarge.into());
@ -611,7 +613,7 @@ where
// Malformed requests should be responded with 400
this.messages.push_back(DispatcherMessage::Error(
Response::BadRequest().finish().drop_body(),
Response::bad_request().drop_body(),
));
this.flags.insert(Flags::READ_DISCONNECT);
*this.error = Some(err.into());
@ -684,7 +686,8 @@ where
if !this.flags.contains(Flags::STARTED) {
trace!("Slow request timeout");
let _ = self.as_mut().send_response(
Response::RequestTimeout().finish().drop_body(),
Response::new(StatusCode::REQUEST_TIMEOUT)
.drop_body(),
ResponseBody::Other(Body::Empty),
);
this = self.project();
@ -951,6 +954,7 @@ mod tests {
use actix_service::fn_service;
use actix_utils::future::{ready, Ready};
use bytes::Bytes;
use futures_util::future::lazy;
use super::*;
@ -979,19 +983,21 @@ mod tests {
}
fn ok_service() -> impl Service<Request, Response = Response<Body>, Error = Error> {
fn_service(|_req: Request| ready(Ok::<_, Error>(Response::Ok().finish())))
fn_service(|_req: Request| ready(Ok::<_, Error>(Response::ok())))
}
fn echo_path_service(
) -> impl Service<Request, Response = Response<Body>, Error = Error> {
fn_service(|req: Request| {
let path = req.path().as_bytes();
ready(Ok::<_, Error>(Response::Ok().body(Body::from_slice(path))))
ready(Ok::<_, Error>(
Response::ok().set_body(Body::from_slice(path)),
))
})
}
fn echo_payload_service(
) -> impl Service<Request, Response = Response<Body>, Error = Error> {
) -> impl Service<Request, Response = Response<Bytes>, Error = Error> {
fn_service(|mut req: Request| {
Box::pin(async move {
use futures_util::stream::StreamExt as _;
@ -1002,7 +1008,7 @@ mod tests {
body.extend_from_slice(chunk.unwrap().chunk())
}
Ok::<_, Error>(Response::Ok().body(body))
Ok::<_, Error>(Response::ok().set_body(body.freeze()))
})
})
}

View File

@ -1,104 +0,0 @@
//! Status code based HTTP response builders.
#![allow(non_upper_case_globals)]
use http::StatusCode;
use crate::{
body::Body,
response::{Response, ResponseBuilder},
};
macro_rules! static_resp {
($name:ident, $status:expr) => {
#[allow(non_snake_case, missing_docs)]
pub fn $name() -> ResponseBuilder {
ResponseBuilder::new($status)
}
};
}
impl Response<Body> {
static_resp!(Continue, StatusCode::CONTINUE);
static_resp!(SwitchingProtocols, StatusCode::SWITCHING_PROTOCOLS);
static_resp!(Processing, StatusCode::PROCESSING);
static_resp!(Ok, StatusCode::OK);
static_resp!(Created, StatusCode::CREATED);
static_resp!(Accepted, StatusCode::ACCEPTED);
static_resp!(
NonAuthoritativeInformation,
StatusCode::NON_AUTHORITATIVE_INFORMATION
);
static_resp!(NoContent, StatusCode::NO_CONTENT);
static_resp!(ResetContent, StatusCode::RESET_CONTENT);
static_resp!(PartialContent, StatusCode::PARTIAL_CONTENT);
static_resp!(MultiStatus, StatusCode::MULTI_STATUS);
static_resp!(AlreadyReported, StatusCode::ALREADY_REPORTED);
static_resp!(MultipleChoices, StatusCode::MULTIPLE_CHOICES);
static_resp!(MovedPermanently, StatusCode::MOVED_PERMANENTLY);
static_resp!(Found, StatusCode::FOUND);
static_resp!(SeeOther, StatusCode::SEE_OTHER);
static_resp!(NotModified, StatusCode::NOT_MODIFIED);
static_resp!(UseProxy, StatusCode::USE_PROXY);
static_resp!(TemporaryRedirect, StatusCode::TEMPORARY_REDIRECT);
static_resp!(PermanentRedirect, StatusCode::PERMANENT_REDIRECT);
static_resp!(BadRequest, StatusCode::BAD_REQUEST);
static_resp!(NotFound, StatusCode::NOT_FOUND);
static_resp!(Unauthorized, StatusCode::UNAUTHORIZED);
static_resp!(PaymentRequired, StatusCode::PAYMENT_REQUIRED);
static_resp!(Forbidden, StatusCode::FORBIDDEN);
static_resp!(MethodNotAllowed, StatusCode::METHOD_NOT_ALLOWED);
static_resp!(NotAcceptable, StatusCode::NOT_ACCEPTABLE);
static_resp!(
ProxyAuthenticationRequired,
StatusCode::PROXY_AUTHENTICATION_REQUIRED
);
static_resp!(RequestTimeout, StatusCode::REQUEST_TIMEOUT);
static_resp!(Conflict, StatusCode::CONFLICT);
static_resp!(Gone, StatusCode::GONE);
static_resp!(LengthRequired, StatusCode::LENGTH_REQUIRED);
static_resp!(PreconditionFailed, StatusCode::PRECONDITION_FAILED);
static_resp!(PreconditionRequired, StatusCode::PRECONDITION_REQUIRED);
static_resp!(PayloadTooLarge, StatusCode::PAYLOAD_TOO_LARGE);
static_resp!(UriTooLong, StatusCode::URI_TOO_LONG);
static_resp!(UnsupportedMediaType, StatusCode::UNSUPPORTED_MEDIA_TYPE);
static_resp!(RangeNotSatisfiable, StatusCode::RANGE_NOT_SATISFIABLE);
static_resp!(ExpectationFailed, StatusCode::EXPECTATION_FAILED);
static_resp!(UnprocessableEntity, StatusCode::UNPROCESSABLE_ENTITY);
static_resp!(TooManyRequests, StatusCode::TOO_MANY_REQUESTS);
static_resp!(
RequestHeaderFieldsTooLarge,
StatusCode::REQUEST_HEADER_FIELDS_TOO_LARGE
);
static_resp!(
UnavailableForLegalReasons,
StatusCode::UNAVAILABLE_FOR_LEGAL_REASONS
);
static_resp!(InternalServerError, StatusCode::INTERNAL_SERVER_ERROR);
static_resp!(NotImplemented, StatusCode::NOT_IMPLEMENTED);
static_resp!(BadGateway, StatusCode::BAD_GATEWAY);
static_resp!(ServiceUnavailable, StatusCode::SERVICE_UNAVAILABLE);
static_resp!(GatewayTimeout, StatusCode::GATEWAY_TIMEOUT);
static_resp!(VersionNotSupported, StatusCode::HTTP_VERSION_NOT_SUPPORTED);
static_resp!(VariantAlsoNegotiates, StatusCode::VARIANT_ALSO_NEGOTIATES);
static_resp!(InsufficientStorage, StatusCode::INSUFFICIENT_STORAGE);
static_resp!(LoopDetected, StatusCode::LOOP_DETECTED);
}
#[cfg(test)]
mod tests {
use crate::body::Body;
use crate::response::Response;
use http::StatusCode;
#[test]
fn test_build() {
let resp = Response::Ok().body(Body::Empty);
assert_eq!(resp.status(), StatusCode::OK);
}
}

View File

@ -37,7 +37,6 @@ pub mod encoding;
mod extensions;
mod header;
mod helpers;
mod http_codes;
mod http_message;
mod message;
mod payload;

View File

@ -29,18 +29,6 @@ pub struct Response<B> {
}
impl Response<Body> {
/// Create HTTP response builder with specific status.
#[inline]
pub fn build(status: StatusCode) -> ResponseBuilder {
ResponseBuilder::new(status)
}
/// Create HTTP response builder
#[inline]
pub fn build_from<T: Into<ResponseBuilder>>(source: T) -> ResponseBuilder {
source.into()
}
/// Constructs a response
#[inline]
pub fn new(status: StatusCode) -> Response<Body> {
@ -51,6 +39,41 @@ impl Response<Body> {
}
}
/// Create HTTP response builder with specific status.
#[inline]
pub fn build(status: StatusCode) -> ResponseBuilder {
ResponseBuilder::new(status)
}
// just a couple frequently used shortcuts
// this list should not grow larger than a few
/// Creates a new response with status 200 OK.
#[inline]
pub fn ok() -> Response<Body> {
Response::new(StatusCode::OK)
}
/// Creates a new response with status 400 Bad Request.
#[inline]
pub fn bad_request() -> Response<Body> {
Response::new(StatusCode::BAD_REQUEST)
}
/// Creates a new response with status 404 Not Found.
#[inline]
pub fn not_found() -> Response<Body> {
Response::new(StatusCode::NOT_FOUND)
}
/// Creates a new response with status 500 Internal Server Error.
#[inline]
pub fn internal_server_error() -> Response<Body> {
Response::new(StatusCode::INTERNAL_SERVER_ERROR)
}
// end shortcuts
/// Constructs an error response
#[inline]
pub fn from_error(error: Error) -> Response<Body> {
@ -281,9 +304,9 @@ impl ResponseBuilder {
///
/// ```
/// # use actix_http::Response;
/// use actix_http::http::header;
/// use actix_http::http::{header, StatusCode};
///
/// Response::Ok()
/// Response::build(StatusCode::OK)
/// .insert_header((header::CONTENT_TYPE, mime::APPLICATION_JSON))
/// .insert_header(("X-TEST", "value"))
/// .finish();
@ -308,9 +331,9 @@ impl ResponseBuilder {
///
/// ```
/// # use actix_http::Response;
/// use actix_http::http::header;
/// use actix_http::http::{header, StatusCode};
///
/// Response::Ok()
/// Response::build(StatusCode::OK)
/// .append_header((header::CONTENT_TYPE, mime::APPLICATION_JSON))
/// .append_header(("X-TEST", "value1"))
/// .append_header(("X-TEST", "value2"))
@ -557,7 +580,7 @@ impl From<ResponseBuilder> for Response<Body> {
impl From<&'static str> for Response<Body> {
fn from(val: &'static str) -> Self {
Response::Ok()
Response::build(StatusCode::OK)
.content_type(mime::TEXT_PLAIN_UTF_8)
.body(val)
}
@ -565,7 +588,7 @@ impl From<&'static str> for Response<Body> {
impl From<&'static [u8]> for Response<Body> {
fn from(val: &'static [u8]) -> Self {
Response::Ok()
Response::build(StatusCode::OK)
.content_type(mime::APPLICATION_OCTET_STREAM)
.body(val)
}
@ -573,7 +596,7 @@ impl From<&'static [u8]> for Response<Body> {
impl From<String> for Response<Body> {
fn from(val: String) -> Self {
Response::Ok()
Response::build(StatusCode::OK)
.content_type(mime::TEXT_PLAIN_UTF_8)
.body(val)
}
@ -581,7 +604,7 @@ impl From<String> for Response<Body> {
impl<'a> From<&'a String> for Response<Body> {
fn from(val: &'a String) -> Self {
Response::Ok()
Response::build(StatusCode::OK)
.content_type(mime::TEXT_PLAIN_UTF_8)
.body(val)
}
@ -589,7 +612,7 @@ impl<'a> From<&'a String> for Response<Body> {
impl From<Bytes> for Response<Body> {
fn from(val: Bytes) -> Self {
Response::Ok()
Response::build(StatusCode::OK)
.content_type(mime::APPLICATION_OCTET_STREAM)
.body(val)
}
@ -597,7 +620,7 @@ impl From<Bytes> for Response<Body> {
impl From<BytesMut> for Response<Body> {
fn from(val: BytesMut) -> Self {
Response::Ok()
Response::build(StatusCode::OK)
.content_type(mime::APPLICATION_OCTET_STREAM)
.body(val)
}
@ -611,7 +634,7 @@ mod tests {
#[test]
fn test_debug() {
let resp = Response::Ok()
let resp = Response::build(StatusCode::OK)
.append_header((COOKIE, HeaderValue::from_static("cookie1=value1; ")))
.append_header((COOKIE, HeaderValue::from_static("cookie2=value2; ")))
.finish();
@ -621,7 +644,9 @@ mod tests {
#[test]
fn test_basic_builder() {
let resp = Response::Ok().insert_header(("X-TEST", "value")).finish();
let resp = Response::build(StatusCode::OK)
.insert_header(("X-TEST", "value"))
.finish();
assert_eq!(resp.status(), StatusCode::OK);
}
@ -741,7 +766,7 @@ mod tests {
#[test]
fn response_builder_header_insert_kv() {
let mut res = Response::Ok();
let mut res = Response::build(StatusCode::OK);
res.insert_header(("Content-Type", "application/octet-stream"));
let res = res.finish();
@ -753,7 +778,7 @@ mod tests {
#[test]
fn response_builder_header_insert_typed() {
let mut res = Response::Ok();
let mut res = Response::build(StatusCode::OK);
res.insert_header((header::CONTENT_TYPE, mime::APPLICATION_OCTET_STREAM));
let res = res.finish();
@ -765,7 +790,7 @@ mod tests {
#[test]
fn response_builder_header_append_kv() {
let mut res = Response::Ok();
let mut res = Response::build(StatusCode::OK);
res.append_header(("Content-Type", "application/octet-stream"));
res.append_header(("Content-Type", "application/json"));
let res = res.finish();
@ -778,7 +803,7 @@ mod tests {
#[test]
fn response_builder_header_append_typed() {
let mut res = Response::Ok();
let mut res = Response::build(StatusCode::OK);
res.append_header((header::CONTENT_TYPE, mime::APPLICATION_OCTET_STREAM));
res.append_header((header::CONTENT_TYPE, mime::APPLICATION_JSON));
let res = res.finish();

View File

@ -101,29 +101,37 @@ pub enum HandshakeError {
impl ResponseError for HandshakeError {
fn error_response(&self) -> Response<Body> {
match self {
HandshakeError::GetMethodRequired => Response::MethodNotAllowed()
.insert_header((header::ALLOW, "GET"))
.finish(),
HandshakeError::GetMethodRequired => {
Response::build(StatusCode::METHOD_NOT_ALLOWED)
.insert_header((header::ALLOW, "GET"))
.finish()
}
HandshakeError::NoWebsocketUpgrade => Response::BadRequest()
.reason("No WebSocket Upgrade header found")
.finish(),
HandshakeError::NoWebsocketUpgrade => {
Response::build(StatusCode::BAD_REQUEST)
.reason("No WebSocket Upgrade header found")
.finish()
}
HandshakeError::NoConnectionUpgrade => Response::BadRequest()
.reason("No Connection upgrade")
.finish(),
HandshakeError::NoConnectionUpgrade => {
Response::build(StatusCode::BAD_REQUEST)
.reason("No Connection upgrade")
.finish()
}
HandshakeError::NoVersionHeader => Response::BadRequest()
HandshakeError::NoVersionHeader => Response::build(StatusCode::BAD_REQUEST)
.reason("WebSocket version header is required")
.finish(),
HandshakeError::UnsupportedVersion => Response::BadRequest()
.reason("Unsupported WebSocket version")
.finish(),
HandshakeError::BadWebsocketKey => {
Response::BadRequest().reason("Handshake error").finish()
HandshakeError::UnsupportedVersion => {
Response::build(StatusCode::BAD_REQUEST)
.reason("Unsupported WebSocket version")
.finish()
}
HandshakeError::BadWebsocketKey => Response::build(StatusCode::BAD_REQUEST)
.reason("Handshake error")
.finish(),
}
}
}

View File

@ -33,7 +33,7 @@ const STR: &str = "Hello World Hello World Hello World Hello World Hello World \
async fn test_h1_v2() {
let srv = test_server(move || {
HttpService::build()
.finish(|_| future::ok::<_, ()>(Response::Ok().body(STR)))
.finish(|_| future::ok::<_, ()>(Response::ok().set_body(STR)))
.tcp()
})
.await;
@ -61,7 +61,7 @@ async fn test_h1_v2() {
async fn test_connection_close() {
let srv = test_server(move || {
HttpService::build()
.finish(|_| future::ok::<_, ()>(Response::Ok().body(STR)))
.finish(|_| future::ok::<_, ()>(Response::ok().set_body(STR)))
.tcp()
.map(|_| ())
})
@ -77,9 +77,9 @@ async fn test_with_query_parameter() {
HttpService::build()
.finish(|req: Request| {
if req.uri().query().unwrap().contains("qp=") {
future::ok::<_, ()>(Response::Ok().finish())
future::ok::<_, ()>(Response::ok())
} else {
future::ok::<_, ()>(Response::BadRequest().finish())
future::ok::<_, ()>(Response::bad_request())
}
})
.tcp()
@ -112,7 +112,7 @@ async fn test_h1_expect() {
let str = std::str::from_utf8(&buf).unwrap();
assert_eq!(str, "expect body");
Ok::<_, ()>(Response::Ok().finish())
Ok::<_, ()>(Response::ok())
})
.tcp()
})

View File

@ -71,7 +71,7 @@ fn tls_config() -> SslAcceptor {
async fn test_h2() -> io::Result<()> {
let srv = test_server(move || {
HttpService::build()
.h2(|_| ok::<_, Error>(Response::Ok().finish()))
.h2(|_| ok::<_, Error>(Response::ok()))
.openssl(tls_config())
.map_err(|_| ())
})
@ -89,7 +89,7 @@ async fn test_h2_1() -> io::Result<()> {
.finish(|req: Request| {
assert!(req.peer_addr().is_some());
assert_eq!(req.version(), Version::HTTP_2);
ok::<_, Error>(Response::Ok().finish())
ok::<_, Error>(Response::ok())
})
.openssl(tls_config())
.map_err(|_| ())
@ -108,7 +108,7 @@ async fn test_h2_body() -> io::Result<()> {
HttpService::build()
.h2(|mut req: Request<_>| async move {
let body = load_body(req.take_payload()).await?;
Ok::<_, Error>(Response::Ok().body(body))
Ok::<_, Error>(Response::ok().set_body(body))
})
.openssl(tls_config())
.map_err(|_| ())
@ -186,7 +186,7 @@ async fn test_h2_headers() {
let mut srv = test_server(move || {
let data = data.clone();
HttpService::build().h2(move |_| {
let mut builder = Response::Ok();
let mut builder = Response::build(StatusCode::OK);
for idx in 0..90 {
builder.insert_header(
(format!("X-TEST-{}", idx).as_str(),
@ -245,7 +245,7 @@ const STR: &str = "Hello World Hello World Hello World Hello World Hello World \
async fn test_h2_body2() {
let mut srv = test_server(move || {
HttpService::build()
.h2(|_| ok::<_, ()>(Response::Ok().body(STR)))
.h2(|_| ok::<_, ()>(Response::ok().set_body(STR)))
.openssl(tls_config())
.map_err(|_| ())
})
@ -263,7 +263,7 @@ async fn test_h2_body2() {
async fn test_h2_head_empty() {
let mut srv = test_server(move || {
HttpService::build()
.finish(|_| ok::<_, ()>(Response::Ok().body(STR)))
.finish(|_| ok::<_, ()>(Response::ok().set_body(STR)))
.openssl(tls_config())
.map_err(|_| ())
})
@ -287,7 +287,7 @@ async fn test_h2_head_empty() {
async fn test_h2_head_binary() {
let mut srv = test_server(move || {
HttpService::build()
.h2(|_| ok::<_, ()>(Response::Ok().body(STR)))
.h2(|_| ok::<_, ()>(Response::ok().set_body(STR)))
.openssl(tls_config())
.map_err(|_| ())
})
@ -310,7 +310,7 @@ async fn test_h2_head_binary() {
async fn test_h2_head_binary2() {
let srv = test_server(move || {
HttpService::build()
.h2(|_| ok::<_, ()>(Response::Ok().body(STR)))
.h2(|_| ok::<_, ()>(Response::ok().set_body(STR)))
.openssl(tls_config())
.map_err(|_| ())
})
@ -332,7 +332,7 @@ async fn test_h2_body_length() {
.h2(|_| {
let body = once(ok(Bytes::from_static(STR.as_ref())));
ok::<_, ()>(
Response::Ok().body(SizedStream::new(STR.len() as u64, body)),
Response::ok().set_body(SizedStream::new(STR.len() as u64, body)),
)
})
.openssl(tls_config())
@ -355,7 +355,7 @@ async fn test_h2_body_chunked_explicit() {
.h2(|_| {
let body = once(ok::<_, Error>(Bytes::from_static(STR.as_ref())));
ok::<_, ()>(
Response::Ok()
Response::build(StatusCode::OK)
.insert_header((header::TRANSFER_ENCODING, "chunked"))
.streaming(body),
)
@ -383,7 +383,7 @@ async fn test_h2_response_http_error_handling() {
.h2(fn_service(|_| {
let broken_header = Bytes::from_static(b"\0\0\0");
ok::<_, ()>(
Response::Ok()
Response::build(StatusCode::OK)
.insert_header((header::CONTENT_TYPE, broken_header))
.body(STR),
)
@ -428,7 +428,7 @@ async fn test_h2_on_connect() {
})
.h2(|req: Request| {
assert!(req.extensions().contains::<isize>());
ok::<_, ()>(Response::Ok().finish())
ok::<_, ()>(Response::ok())
})
.openssl(tls_config())
.map_err(|_| ())

View File

@ -56,7 +56,7 @@ fn tls_config() -> RustlsServerConfig {
async fn test_h1() -> io::Result<()> {
let srv = test_server(move || {
HttpService::build()
.h1(|_| ok::<_, Error>(Response::Ok().finish()))
.h1(|_| ok::<_, Error>(Response::ok()))
.rustls(tls_config())
})
.await;
@ -70,7 +70,7 @@ async fn test_h1() -> io::Result<()> {
async fn test_h2() -> io::Result<()> {
let srv = test_server(move || {
HttpService::build()
.h2(|_| ok::<_, Error>(Response::Ok().finish()))
.h2(|_| ok::<_, Error>(Response::ok()))
.rustls(tls_config())
})
.await;
@ -87,7 +87,7 @@ async fn test_h1_1() -> io::Result<()> {
.h1(|req: Request| {
assert!(req.peer_addr().is_some());
assert_eq!(req.version(), Version::HTTP_11);
ok::<_, Error>(Response::Ok().finish())
ok::<_, Error>(Response::ok())
})
.rustls(tls_config())
})
@ -105,7 +105,7 @@ async fn test_h2_1() -> io::Result<()> {
.finish(|req: Request| {
assert!(req.peer_addr().is_some());
assert_eq!(req.version(), Version::HTTP_2);
ok::<_, Error>(Response::Ok().finish())
ok::<_, Error>(Response::ok())
})
.rustls(tls_config())
})
@ -123,7 +123,7 @@ async fn test_h2_body1() -> io::Result<()> {
HttpService::build()
.h2(|mut req: Request<_>| async move {
let body = load_body(req.take_payload()).await?;
Ok::<_, Error>(Response::Ok().body(body))
Ok::<_, Error>(Response::ok().set_body(body))
})
.rustls(tls_config())
})
@ -199,7 +199,7 @@ async fn test_h2_headers() {
let mut srv = test_server(move || {
let data = data.clone();
HttpService::build().h2(move |_| {
let mut config = Response::Ok();
let mut config = Response::build(StatusCode::OK);
for idx in 0..90 {
config.insert_header((
format!("X-TEST-{}", idx).as_str(),
@ -257,7 +257,7 @@ const STR: &str = "Hello World Hello World Hello World Hello World Hello World \
async fn test_h2_body2() {
let mut srv = test_server(move || {
HttpService::build()
.h2(|_| ok::<_, ()>(Response::Ok().body(STR)))
.h2(|_| ok::<_, ()>(Response::ok().set_body(STR)))
.rustls(tls_config())
})
.await;
@ -274,7 +274,7 @@ async fn test_h2_body2() {
async fn test_h2_head_empty() {
let mut srv = test_server(move || {
HttpService::build()
.finish(|_| ok::<_, ()>(Response::Ok().body(STR)))
.finish(|_| ok::<_, ()>(Response::ok().set_body(STR)))
.rustls(tls_config())
})
.await;
@ -300,7 +300,7 @@ async fn test_h2_head_empty() {
async fn test_h2_head_binary() {
let mut srv = test_server(move || {
HttpService::build()
.h2(|_| ok::<_, ()>(Response::Ok().body(STR)))
.h2(|_| ok::<_, ()>(Response::ok().set_body(STR)))
.rustls(tls_config())
})
.await;
@ -325,7 +325,7 @@ async fn test_h2_head_binary() {
async fn test_h2_head_binary2() {
let srv = test_server(move || {
HttpService::build()
.h2(|_| ok::<_, ()>(Response::Ok().body(STR)))
.h2(|_| ok::<_, ()>(Response::ok().set_body(STR)))
.rustls(tls_config())
})
.await;
@ -349,7 +349,7 @@ async fn test_h2_body_length() {
.h2(|_| {
let body = once(ok(Bytes::from_static(STR.as_ref())));
ok::<_, ()>(
Response::Ok().body(SizedStream::new(STR.len() as u64, body)),
Response::ok().set_body(SizedStream::new(STR.len() as u64, body)),
)
})
.rustls(tls_config())
@ -371,7 +371,7 @@ async fn test_h2_body_chunked_explicit() {
.h2(|_| {
let body = once(ok::<_, Error>(Bytes::from_static(STR.as_ref())));
ok::<_, ()>(
Response::Ok()
Response::build(StatusCode::OK)
.insert_header((header::TRANSFER_ENCODING, "chunked"))
.streaming(body),
)
@ -399,7 +399,7 @@ async fn test_h2_response_http_error_handling() {
ok::<_, ()>(fn_service(|_| {
let broken_header = Bytes::from_static(b"\0\0\0");
ok::<_, ()>(
Response::Ok()
Response::build(StatusCode::OK)
.insert_header((http::header::CONTENT_TYPE, broken_header))
.body(STR),
)

View File

@ -14,8 +14,8 @@ use regex::Regex;
use actix_http::HttpMessage;
use actix_http::{
body::{Body, SizedStream},
error, http,
http::header,
error,
http::{self, header, StatusCode},
Error, HttpService, KeepAlive, Request, Response,
};
@ -28,7 +28,7 @@ async fn test_h1() {
.client_disconnect(1000)
.h1(|req: Request| {
assert!(req.peer_addr().is_some());
ok::<_, ()>(Response::Ok().finish())
ok::<_, ()>(Response::ok())
})
.tcp()
})
@ -48,7 +48,7 @@ async fn test_h1_2() {
.finish(|req: Request| {
assert!(req.peer_addr().is_some());
assert_eq!(req.version(), http::Version::HTTP_11);
ok::<_, ()>(Response::Ok().finish())
ok::<_, ()>(Response::ok())
})
.tcp()
})
@ -69,7 +69,7 @@ async fn test_expect_continue() {
err(error::ErrorPreconditionFailed("error"))
}
}))
.finish(|_| ok::<_, ()>(Response::Ok().finish()))
.finish(|_| ok::<_, ()>(Response::ok()))
.tcp()
})
.await;
@ -100,7 +100,7 @@ async fn test_expect_continue_h1() {
}
})
}))
.h1(fn_service(|_| ok::<_, ()>(Response::Ok().finish())))
.h1(fn_service(|_| ok::<_, ()>(Response::ok())))
.tcp()
})
.await;
@ -134,7 +134,9 @@ async fn test_chunked_payload() {
})
.fold(0usize, |acc, chunk| ready(acc + chunk.len()))
.map(|req_size| {
Ok::<_, Error>(Response::Ok().body(format!("size={}", req_size)))
Ok::<_, Error>(
Response::ok().set_body(format!("size={}", req_size)),
)
})
}))
.tcp()
@ -179,7 +181,7 @@ async fn test_slow_request() {
let srv = test_server(|| {
HttpService::build()
.client_timeout(100)
.finish(|_| ok::<_, ()>(Response::Ok().finish()))
.finish(|_| ok::<_, ()>(Response::ok()))
.tcp()
})
.await;
@ -195,7 +197,7 @@ async fn test_slow_request() {
async fn test_http1_malformed_request() {
let srv = test_server(|| {
HttpService::build()
.h1(|_| ok::<_, ()>(Response::Ok().finish()))
.h1(|_| ok::<_, ()>(Response::ok()))
.tcp()
})
.await;
@ -211,7 +213,7 @@ async fn test_http1_malformed_request() {
async fn test_http1_keepalive() {
let srv = test_server(|| {
HttpService::build()
.h1(|_| ok::<_, ()>(Response::Ok().finish()))
.h1(|_| ok::<_, ()>(Response::ok()))
.tcp()
})
.await;
@ -233,7 +235,7 @@ async fn test_http1_keepalive_timeout() {
let srv = test_server(|| {
HttpService::build()
.keep_alive(1)
.h1(|_| ok::<_, ()>(Response::Ok().finish()))
.h1(|_| ok::<_, ()>(Response::ok()))
.tcp()
})
.await;
@ -254,7 +256,7 @@ async fn test_http1_keepalive_timeout() {
async fn test_http1_keepalive_close() {
let srv = test_server(|| {
HttpService::build()
.h1(|_| ok::<_, ()>(Response::Ok().finish()))
.h1(|_| ok::<_, ()>(Response::ok()))
.tcp()
})
.await;
@ -275,7 +277,7 @@ async fn test_http1_keepalive_close() {
async fn test_http10_keepalive_default_close() {
let srv = test_server(|| {
HttpService::build()
.h1(|_| ok::<_, ()>(Response::Ok().finish()))
.h1(|_| ok::<_, ()>(Response::ok()))
.tcp()
})
.await;
@ -295,7 +297,7 @@ async fn test_http10_keepalive_default_close() {
async fn test_http10_keepalive() {
let srv = test_server(|| {
HttpService::build()
.h1(|_| ok::<_, ()>(Response::Ok().finish()))
.h1(|_| ok::<_, ()>(Response::ok()))
.tcp()
})
.await;
@ -323,7 +325,7 @@ async fn test_http1_keepalive_disabled() {
let srv = test_server(|| {
HttpService::build()
.keep_alive(KeepAlive::Disabled)
.h1(|_| ok::<_, ()>(Response::Ok().finish()))
.h1(|_| ok::<_, ()>(Response::ok()))
.tcp()
})
.await;
@ -394,7 +396,7 @@ async fn test_h1_headers() {
let mut srv = test_server(move || {
let data = data.clone();
HttpService::build().h1(move |_| {
let mut builder = Response::Ok();
let mut builder = Response::build(StatusCode::OK);
for idx in 0..90 {
builder.insert_header((
format!("X-TEST-{}", idx).as_str(),
@ -451,7 +453,7 @@ const STR: &str = "Hello World Hello World Hello World Hello World Hello World \
async fn test_h1_body() {
let mut srv = test_server(|| {
HttpService::build()
.h1(|_| ok::<_, ()>(Response::Ok().body(STR)))
.h1(|_| ok::<_, ()>(Response::ok().set_body(STR)))
.tcp()
})
.await;
@ -468,7 +470,7 @@ async fn test_h1_body() {
async fn test_h1_head_empty() {
let mut srv = test_server(|| {
HttpService::build()
.h1(|_| ok::<_, ()>(Response::Ok().body(STR)))
.h1(|_| ok::<_, ()>(Response::ok().set_body(STR)))
.tcp()
})
.await;
@ -493,7 +495,7 @@ async fn test_h1_head_empty() {
async fn test_h1_head_binary() {
let mut srv = test_server(|| {
HttpService::build()
.h1(|_| ok::<_, ()>(Response::Ok().body(STR)))
.h1(|_| ok::<_, ()>(Response::ok().set_body(STR)))
.tcp()
})
.await;
@ -518,7 +520,7 @@ async fn test_h1_head_binary() {
async fn test_h1_head_binary2() {
let srv = test_server(|| {
HttpService::build()
.h1(|_| ok::<_, ()>(Response::Ok().body(STR)))
.h1(|_| ok::<_, ()>(Response::ok().set_body(STR)))
.tcp()
})
.await;
@ -542,7 +544,7 @@ async fn test_h1_body_length() {
.h1(|_| {
let body = once(ok(Bytes::from_static(STR.as_ref())));
ok::<_, ()>(
Response::Ok().body(SizedStream::new(STR.len() as u64, body)),
Response::ok().set_body(SizedStream::new(STR.len() as u64, body)),
)
})
.tcp()
@ -564,7 +566,7 @@ async fn test_h1_body_chunked_explicit() {
.h1(|_| {
let body = once(ok::<_, Error>(Bytes::from_static(STR.as_ref())));
ok::<_, ()>(
Response::Ok()
Response::build(StatusCode::OK)
.insert_header((header::TRANSFER_ENCODING, "chunked"))
.streaming(body),
)
@ -598,7 +600,7 @@ async fn test_h1_body_chunked_implicit() {
HttpService::build()
.h1(|_| {
let body = once(ok::<_, Error>(Bytes::from_static(STR.as_ref())));
ok::<_, ()>(Response::Ok().streaming(body))
ok::<_, ()>(Response::build(StatusCode::OK).streaming(body))
})
.tcp()
})
@ -628,7 +630,7 @@ async fn test_h1_response_http_error_handling() {
.h1(fn_service(|_| {
let broken_header = Bytes::from_static(b"\0\0\0");
ok::<_, ()>(
Response::Ok()
Response::build(StatusCode::OK)
.insert_header((http::header::CONTENT_TYPE, broken_header))
.body(STR),
)
@ -671,7 +673,7 @@ async fn test_h1_on_connect() {
})
.h1(|req: Request| {
assert!(req.extensions().contains::<isize>());
ok::<_, ()>(Response::Ok().finish())
ok::<_, ()>(Response::ok())
})
.tcp()
})

View File

@ -91,7 +91,7 @@ async fn test_simple() {
let ws_service = ws_service.clone();
HttpService::build()
.upgrade(fn_factory(move || future::ok::<_, ()>(ws_service.clone())))
.finish(|_| future::ok::<_, ()>(Response::NotFound()))
.finish(|_| future::ok::<_, ()>(Response::not_found()))
.tcp()
}
})