1
0
mirror of https://github.com/actix/actix-extras.git synced 2024-11-28 01:32:57 +01:00

simplify http response construction; deprecate httpcodes

This commit is contained in:
Nikolay Kim 2018-03-30 23:07:33 -07:00
parent 8d8f6bedad
commit 44e3df82f6
58 changed files with 561 additions and 539 deletions

View File

@ -10,7 +10,6 @@ use actix_web::http::header::{CONTENT_TYPE, CONTENT_LENGTH};
use actix_web::{Responder, HttpMessage, HttpRequest, HttpResponse};
use actix_web::dev::HttpResponseBuilder;
use actix_web::error::{Error, PayloadError, ResponseError};
use actix_web::httpcodes::{HttpBadRequest, HttpPayloadTooLarge};
#[derive(Fail, Debug)]
@ -36,8 +35,8 @@ impl ResponseError for ProtoBufPayloadError {
fn error_response(&self) -> HttpResponse {
match *self {
ProtoBufPayloadError::Overflow => HttpPayloadTooLarge.into(),
_ => HttpBadRequest.into(),
ProtoBufPayloadError::Overflow => HttpResponse::PayloadTooLarge().into(),
_ => HttpResponse::BadRequest().into(),
}
}
}

View File

@ -7,9 +7,7 @@ extern crate actix_web;
extern crate env_logger;
use std::env;
use actix_web::{
http, middleware, server,
Application};
use actix_web::{http, middleware, server, Application};
mod user;
use user::info;

View File

@ -1,4 +1,4 @@
use actix_web::*;
use actix_web::{Error, HttpMessage, HttpResponse, HttpRequest};
use futures::Future;
@ -14,6 +14,6 @@ pub fn info(req: HttpRequest) -> Box<Future<Item=HttpResponse, Error=Error>> {
req.json()
.from_err()
.and_then(|res: Info| {
Ok(httpcodes::HttpOk.build().json(res)?)
Ok(HttpResponse::Ok().json(res))
}).responder()
}

View File

@ -23,7 +23,7 @@ Here is an example of a simple middleware that adds request and response headers
# extern crate http;
# extern crate actix_web;
use http::{header, HttpTryFrom};
use actix_web::{Application, HttpRequest, HttpResponse, Result, httpcodes};
use actix_web::{Application, HttpRequest, HttpResponse, Result};
use actix_web::middleware::{Middleware, Started, Response};
struct Headers; // <- Our middleware
@ -53,7 +53,7 @@ impl<S> Middleware<S> for Headers {
fn main() {
Application::new()
.middleware(Headers) // <- Register middleware, this method can be called multiple times
.resource("/", |r| r.h(httpcodes::HttpOk));
.resource("/", |r| r.f(|_| HttpResponse::Ok()));
}
```
@ -135,7 +135,7 @@ the specified header.
```rust
# extern crate actix_web;
use actix_web::{Application, http, httpcodes, middleware};
use actix_web::{http, middleware, Application, HttpResponse};
fn main() {
let app = Application::new()
@ -144,8 +144,8 @@ fn main() {
.header("X-Version", "0.2")
.finish())
.resource("/test", |r| {
r.method(http::Method::GET).f(|req| httpcodes::HttpOk);
r.method(http::Method::HEAD).f(|req| httpcodes::HttpMethodNotAllowed);
r.method(http::Method::GET).f(|req| HttpResponse::Ok());
r.method(http::Method::HEAD).f(|req| HttpResponse::MethodNotAllowed());
})
.finish();
}

View File

@ -112,8 +112,8 @@ fn index(req: HttpRequest<State>) -> Box<Future<Item=HttpResponse, Error=Error>>
.from_err()
.and_then(|res| {
match res {
Ok(user) => Ok(httpcodes::HttpOk.build().json(user)?),
Err(_) => Ok(httpcodes::HttpInternalServerError.into())
Ok(user) => Ok(HttpResponse::Ok().json(user)),
Err(_) => Ok(HttpResponse::InternalServerError().into())
}
})
.responder()

View File

@ -72,7 +72,7 @@ Here is full source of main.rs file:
```rust
# use std::thread;
extern crate actix_web;
use actix_web::*;
use actix_web::{Application, HttpRequest, HttpResponse, HttpServer};
fn index(req: HttpRequest) -> &'static str {
"Hello world!"

View File

@ -19,7 +19,7 @@ but path `/application` would not match.
```rust,ignore
# extern crate actix_web;
# extern crate tokio_core;
# use actix_web::*;
# use actix_web::{*, http::Method};
# fn index(req: HttpRequest) -> &'static str {
# "Hello world!"
# }
@ -43,18 +43,18 @@ Multiple applications can be served with one server:
# extern crate tokio_core;
# use tokio_core::net::TcpStream;
# use std::net::SocketAddr;
use actix_web::*;
use actix_web::{Application, HttpResponse, HttpServer};
fn main() {
HttpServer::new(|| vec![
Application::new()
.prefix("/app1")
.resource("/", |r| r.f(|r| httpcodes::HttpOk)),
.resource("/", |r| r.f(|r| HttpResponse::Ok())),
Application::new()
.prefix("/app2")
.resource("/", |r| r.f(|r| httpcodes::HttpOk)),
.resource("/", |r| r.f(|r| HttpResponse::Ok())),
Application::new()
.resource("/", |r| r.f(|r| httpcodes::HttpOk)),
.resource("/", |r| r.f(|r| HttpResponse::Ok())),
]);
}
```

View File

@ -13,14 +13,14 @@ within a properly configured actix system:
# extern crate actix;
# extern crate actix_web;
use actix::*;
use actix_web::*;
use actix_web::{server, Application, HttpResponse};
fn main() {
let sys = actix::System::new("guide");
HttpServer::new(
server::new(
|| Application::new()
.resource("/", |r| r.h(httpcodes::HttpOk)))
.resource("/", |r| r.f(|_| HttpResponse::Ok())))
.bind("127.0.0.1:59080").unwrap()
.start();
@ -46,18 +46,19 @@ address of the started http server. Actix http server accepts several messages:
# extern crate actix;
# extern crate actix_web;
# use futures::Future;
use actix_web::*;
use std::thread;
use std::sync::mpsc;
use actix::*;
use actix_web::{server, Application, HttpResponse, HttpServer};
fn main() {
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
let sys = actix::System::new("http-server");
let addr = HttpServer::new(
let addr = server::new(
|| Application::new()
.resource("/", |r| r.h(httpcodes::HttpOk)))
.resource("/", |r| r.f(|_| HttpResponse::Ok())))
.bind("127.0.0.1:0").expect("Can not bind to 127.0.0.1:0")
.shutdown_timeout(60) // <- Set shutdown timeout to 60 seconds
.start();
@ -80,12 +81,12 @@ can be overridden with the `HttpServer::threads()` method.
```rust
# extern crate actix_web;
# extern crate tokio_core;
use actix_web::*;
use actix_web::{Application, HttpServer, HttpResponse};
fn main() {
HttpServer::new(
|| Application::new()
.resource("/", |r| r.h(httpcodes::HttpOk)))
.resource("/", |r| r.f(|_| HttpResponse::Ok())))
.threads(4); // <- Start 4 workers
}
```
@ -109,16 +110,16 @@ use std::fs::File;
use actix_web::*;
fn main() {
let mut file = File::open("identity.pfx").unwrap();
let mut pkcs12 = vec![];
file.read_to_end(&mut pkcs12).unwrap();
let pkcs12 = Pkcs12::from_der(&pkcs12).unwrap().parse("12345").unwrap();
// load ssl keys
let mut builder = SslAcceptor::mozilla_intermediate(SslMethod::tls()).unwrap();
builder.set_private_key_file("key.pem", SslFiletype::PEM).unwrap();
builder.set_certificate_chain_file("cert.pem").unwrap();
HttpServer::new(
|| Application::new()
.resource("/index.html", |r| r.f(index)))
.bind("127.0.0.1:8080").unwrap()
.serve_ssl(pkcs12).unwrap();
.serve_ssl(builder).unwrap();
}
```
@ -142,22 +143,22 @@ connection behavior is defined by server settings.
```rust
# extern crate actix_web;
# extern crate tokio_core;
use actix_web::*;
use actix_web::{server, Application, HttpResponse};
fn main() {
HttpServer::new(||
server::new(||
Application::new()
.resource("/", |r| r.h(httpcodes::HttpOk)))
.resource("/", |r| r.f(|_| HttpResponse::Ok())))
.keep_alive(75); // <- Set keep-alive to 75 seconds
HttpServer::new(||
server::new(||
Application::new()
.resource("/", |r| r.h(httpcodes::HttpOk)))
.resource("/", |r| r.f(|_| HttpResponse::Ok())))
.keep_alive(server::KeepAlive::Tcp(75)); // <- Use `SO_KEEPALIVE` socket option.
HttpServer::new(||
server::new(||
Application::new()
.resource("/", |r| r.h(httpcodes::HttpOk)))
.resource("/", |r| r.f(|_| HttpResponse::Ok())))
.keep_alive(None); // <- Disable keep-alive
}
```
@ -172,13 +173,13 @@ and is on for *HTTP/1.1* and *HTTP/2.0*.
```rust
# extern crate actix_web;
use actix_web::{HttpRequest, HttpResponse, http, httpcodes::HttpOk};
use actix_web::{HttpRequest, HttpResponse, http};
fn index(req: HttpRequest) -> HttpResponse {
HttpOk.build()
HttpResponse::Ok()
.connection_type(http::ConnectionType::Close) // <- Close connection
.force_close() // <- Alternative method
.finish().unwrap()
.finish()
}
# fn main() {}
```

View File

@ -52,10 +52,8 @@ of application state objects and handler objects.
Here is an example of a handler that stores the number of processed requests:
```rust
# extern crate actix;
# extern crate actix_web;
use actix_web::*;
use actix_web::dev::Handler;
use actix_web::{Application, HttpRequest, HttpResponse, dev::Handler};
struct MyHandler(usize);
@ -65,7 +63,7 @@ impl<S> Handler<S> for MyHandler {
/// Handle request
fn handle(&mut self, req: HttpRequest<S>) -> Self::Result {
self.0 += 1;
httpcodes::HttpOk.into()
HttpResponse::Ok().into()
}
}
# fn main() {}
@ -77,8 +75,7 @@ number of requests processed per thread. A proper implementation would use `Arc`
```rust
# extern crate actix;
# extern crate actix_web;
use actix_web::*;
use actix_web::dev::Handler;
use actix_web::{server, Application, HttpRequest, HttpResponse, dev::Handler};
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
@ -90,7 +87,7 @@ impl<S> Handler<S> for MyHandler {
/// Handle request
fn handle(&mut self, req: HttpRequest<S>) -> Self::Result {
self.0.fetch_add(1, Ordering::Relaxed);
httpcodes::HttpOk.into()
HttpResponse::Ok().into()
}
}
@ -99,7 +96,7 @@ fn main() {
let inc = Arc::new(AtomicUsize::new(0));
HttpServer::new(
server::new(
move || {
let cloned = inc.clone();
Application::new()
@ -148,7 +145,7 @@ impl Responder for MyObj {
// Create response and set content type
Ok(HttpResponse::Ok()
.content_type("application/json")
.body(body)?)
.body(body))
}
}
@ -189,10 +186,9 @@ that implements the [*Responder*](../actix_web/trait.Responder.html) trait. In t
# use futures::future::{Future, result};
fn index(req: HttpRequest) -> Box<Future<Item=HttpResponse, Error=Error>> {
result(HttpResponse::Ok()
result(Ok(HttpResponse::Ok()
.content_type("text/html")
.body(format!("Hello!"))
.map_err(|e| e.into()))
.body(format!("Hello!"))))
.responder()
}
@ -224,7 +220,7 @@ fn index(req: HttpRequest) -> HttpResponse {
HttpResponse::Ok()
.content_type("application/json")
.body(Body::Streaming(Box::new(body))).unwrap()
.body(Body::Streaming(Box::new(body)))
}
fn main() {
@ -253,9 +249,9 @@ fn index(req: HttpRequest) -> Result<Box<Future<Item=HttpResponse, Error=Error>>
Err(error::ErrorBadRequest("bad request"))
} else {
Ok(Box::new(
result(HttpResponse::Ok()
result(Ok(HttpResponse::Ok()
.content_type("text/html")
.body(format!("Hello!")))))
.body(format!("Hello!"))))))
}
}
#
@ -281,20 +277,19 @@ For this case the [*Either*](../actix_web/enum.Either.html) type can be used.
# use actix_web::*;
# use futures::future::Future;
use futures::future::result;
use actix_web::{Either, Error, HttpResponse, httpcodes};
use actix_web::{Either, Error, HttpResponse};
type RegisterResult = Either<HttpResponse, Box<Future<Item=HttpResponse, Error=Error>>>;
fn index(req: HttpRequest) -> RegisterResult {
if is_a_variant() { // <- choose variant A
Either::A(
httpcodes::HttpBadRequest.with_body("Bad data"))
HttpResponse::BadRequest().body("Bad data"))
} else {
Either::B( // <- variant B
result(HttpResponse::Ok()
result(Ok(HttpResponse::Ok()
.content_type("text/html")
.body(format!("Hello!"))
.map_err(|e| e.into())).responder())
.body(format!("Hello!")))).responder())
}
}
# fn is_a_variant() -> bool { true }

View File

@ -70,7 +70,7 @@ to return different responses for different types of errors.
```rust
# extern crate actix_web;
#[macro_use] extern crate failure;
use actix_web::{Application, Body, HttpRequest, HttpResponse, http, error};
use actix_web::{Application, HttpRequest, HttpResponse, http, error};
#[derive(Fail, Debug)]
enum MyError {
@ -86,11 +86,11 @@ impl error::ResponseError for MyError {
fn error_response(&self) -> HttpResponse {
match *self {
MyError::InternalError => HttpResponse::new(
http::StatusCode::INTERNAL_SERVER_ERROR, Body::Empty),
http::StatusCode::INTERNAL_SERVER_ERROR),
MyError::BadClientData => HttpResponse::new(
http::StatusCode::BAD_REQUEST, Body::Empty),
http::StatusCode::BAD_REQUEST),
MyError::Timeout => HttpResponse::new(
http::StatusCode::GATEWAY_TIMEOUT, Body::Empty),
http::StatusCode::GATEWAY_TIMEOUT),
}
}
}

View File

@ -22,7 +22,6 @@ and a resource configuration function.
```rust
# extern crate actix_web;
# use actix_web::{Application, HttpRequest, HttpResponse, http::Method};
# use actix_web::httpcodes::HttpOk;
#
# fn index(req: HttpRequest) -> HttpResponse {
# unimplemented!()
@ -32,7 +31,7 @@ fn main() {
Application::new()
.resource("/prefix", |r| r.f(index))
.resource("/user/{name}",
|r| r.method(Method::GET).f(|req| HttpOk))
|r| r.method(Method::GET).f(|req| HttpResponse::Ok()))
.finish();
}
```
@ -62,7 +61,6 @@ any number of *predicates* but only one handler.
```rust
# extern crate actix_web;
# use actix_web::*;
# use actix_web::httpcodes::*;
fn main() {
Application::new()
@ -70,13 +68,13 @@ fn main() {
resource.route()
.filter(pred::Get())
.filter(pred::Header("content-type", "text/plain"))
.f(|req| HttpOk)
.f(|req| HttpResponse::Ok())
)
.finish();
}
```
In this example `HttpOk` is returned for *GET* requests,
In this example `HttpResponse::Ok()` is returned for *GET* requests,
if request contains `Content-Type` header and value of this header is *text/plain*
and path equals to `/path`. Resource calls handle of the first matching route.
If a resource can not match any route a "NOT FOUND" response is returned.
@ -367,18 +365,17 @@ resource with the name "foo" and the pattern "{a}/{b}/{c}", you might do this:
```rust
# extern crate actix_web;
# use actix_web::{Application, HttpRequest, HttpResponse, http::Method};
# use actix_web::httpcodes::HttpOk;
#
fn index(req: HttpRequest) -> HttpResponse {
let url = req.url_for("foo", &["1", "2", "3"]); // <- generate url for "foo" resource
HttpOk.into()
HttpResponse::Ok().into()
}
fn main() {
let app = Application::new()
.resource("/test/{a}/{b}/{c}", |r| {
r.name("foo"); // <- set resource name, then it could be used in `url_for`
r.method(Method::GET).f(|_| HttpOk);
r.method(Method::GET).f(|_| HttpResponse::Ok());
})
.finish();
}
@ -397,12 +394,12 @@ for URL generation purposes only and are never considered for matching at reques
```rust
# extern crate actix_web;
use actix_web::*;
use actix_web::{Application, HttpRequest, HttpResponse, Error};
fn index(mut req: HttpRequest) -> Result<HttpResponse> {
fn index(mut req: HttpRequest) -> Result<HttpResponse, Error> {
let url = req.url_for("youtube", &["oHg5SJYRHA0"])?;
assert_eq!(url.as_str(), "https://youtube.com/watch/oHg5SJYRHA0");
Ok(httpcodes::HttpOk.into())
Ok(HttpResponse::Ok().into())
}
fn main() {
@ -439,8 +436,8 @@ This handler designed to be use as a handler for application's *default resource
# use actix_web::*;
use actix_web::http::NormalizePath;
#
# fn index(req: HttpRequest) -> httpcodes::StaticResponse {
# httpcodes::HttpOk
# fn index(req: HttpRequest) -> HttpResponse {
# HttpResponse::Ok().into()
# }
fn main() {
let app = Application::new()
@ -462,10 +459,10 @@ It is possible to register path normalization only for *GET* requests only:
```rust
# extern crate actix_web;
# #[macro_use] extern crate serde_derive;
use actix_web::{Application, HttpRequest, http::Method, http::NormalizePath, httpcodes};
use actix_web::{Application, HttpRequest, http::Method, http::NormalizePath};
#
# fn index(req: HttpRequest) -> httpcodes::StaticResponse {
# httpcodes::HttpOk
# fn index(req: HttpRequest) -> &'static str {
# "test"
# }
fn main() {
let app = Application::new()
@ -519,18 +516,15 @@ Here is a simple predicate that check that a request contains a specific *header
```rust
# extern crate actix_web;
# extern crate http;
# use actix_web::*;
# use actix_web::httpcodes::*;
use http::header::CONTENT_TYPE;
use actix_web::pred::Predicate;
use actix_web::{http, pred::Predicate, Application, HttpRequest};
struct ContentTypeHeader;
impl<S: 'static> Predicate<S> for ContentTypeHeader {
fn check(&self, req: &mut HttpRequest<S>) -> bool {
req.headers().contains_key(CONTENT_TYPE)
req.headers().contains_key(http::header::CONTENT_TYPE)
}
}
@ -539,7 +533,7 @@ fn main() {
.resource("/index.html", |r|
r.route()
.filter(ContentTypeHeader)
.h(HttpOk));
.f(|_| HttpResponse::Ok()));
}
```
@ -559,15 +553,14 @@ except "GET":
# extern crate actix_web;
# extern crate http;
# use actix_web::*;
# use actix_web::httpcodes::*;
use actix_web::pred;
use actix_web::{pred, Application, HttpResponse};
fn main() {
Application::new()
.resource("/index.html", |r|
r.route()
.filter(pred::Not(pred::Get()))
.f(|req| HttpMethodNotAllowed))
.f(|req| HttpResponse::MethodNotAllowed()))
.finish();
}
```
@ -596,14 +589,14 @@ with `Application::resource()` method.
```rust
# extern crate actix_web;
use actix_web::{Application, http::Method, pred};
use actix_web::httpcodes::{HttpNotFound, HttpMethodNotAllowed};
use actix_web::{Application, HttpResponse, http::Method, pred};
fn main() {
Application::new()
.default_resource(|r| {
r.method(Method::GET).f(|req| HttpNotFound);
r.route().filter(pred::Not(pred::Get())).f(|req| HttpMethodNotAllowed);
r.method(Method::GET).f(|req| HttpResponse::NotFound());
r.route().filter(pred::Not(pred::Get()))
.f(|req| HttpResponse::MethodNotAllowed());
})
# .finish();
}

View File

@ -19,7 +19,7 @@ fn index(req: HttpRequest) -> HttpResponse {
.content_encoding(ContentEncoding::Br)
.content_type("plain/text")
.header("X-Hdr", "sample")
.body("data").unwrap()
.body("data")
}
# fn main() {}
```
@ -50,7 +50,7 @@ use actix_web::{HttpRequest, HttpResponse, http::ContentEncoding};
fn index(req: HttpRequest) -> HttpResponse {
HttpResponse::Ok()
.content_encoding(ContentEncoding::Br)
.body("data").unwrap()
.body("data")
}
# fn main() {}
```
@ -82,7 +82,7 @@ fn index(mut req: HttpRequest) -> Box<Future<Item=HttpResponse, Error=Error>> {
req.json().from_err()
.and_then(|val: MyObj| {
println!("model: {:?}", val);
Ok(httpcodes::HttpOk.build().json(val)?) // <- send response
Ok(HttpResponse::Ok().json(val)) // <- send response
})
.responder()
}
@ -115,7 +115,7 @@ fn index(req: HttpRequest) -> Box<Future<Item=HttpResponse, Error=Error>> {
// synchronous workflow
.and_then(|body| { // <- body is loaded, now we can deserialize json
let obj = serde_json::from_slice::<MyObj>(&body)?;
Ok(httpcodes::HttpOk.build().json(obj)?) // <- send response
Ok(HttpResponse::Ok().json(obj)) // <- send response
})
.responder()
}
@ -178,7 +178,7 @@ use futures::stream::once;
fn index(req: HttpRequest) -> HttpResponse {
HttpResponse::Ok()
.chunked()
.body(Body::Streaming(Box::new(once(Ok(Bytes::from_static(b"data")))))).unwrap()
.body(Body::Streaming(Box::new(once(Ok(Bytes::from_static(b"data"))))))
}
# fn main() {}
```
@ -249,7 +249,7 @@ fn index(mut req: HttpRequest) -> Box<Future<Item=HttpResponse, Error=Error>> {
.from_err()
.and_then(|params| { // <- url encoded parameters
println!("==== BODY ==== {:?}", params);
ok(httpcodes::HttpOk.into())
ok(HttpResponse::Ok().into())
})
.responder()
}
@ -278,7 +278,7 @@ fn index(mut req: HttpRequest) -> Box<Future<Item=HttpResponse, Error=Error>> {
println!("Chunk: {:?}", chunk);
result::<_, error::PayloadError>(Ok(()))
})
.map(|_| HttpResponse::Ok().finish().unwrap())
.map(|_| HttpResponse::Ok().finish())
.responder()
}
# fn main() {}

View File

@ -11,31 +11,28 @@ You can generate a `HttpRequest` instance with `finish()` or you can
run your handler with `run()` or `run_async()`.
```rust
# extern crate http;
# extern crate actix_web;
use http::{header, StatusCode};
use actix_web::*;
use actix_web::test::TestRequest;
use actix_web::{http, test, HttpRequest, HttpResponse, HttpMessage};
fn index(req: HttpRequest) -> HttpResponse {
if let Some(hdr) = req.headers().get(header::CONTENT_TYPE) {
if let Some(hdr) = req.headers().get(http::header::CONTENT_TYPE) {
if let Ok(s) = hdr.to_str() {
return httpcodes::HttpOk.into()
return HttpResponse::Ok().into()
}
}
httpcodes::HttpBadRequest.into()
HttpResponse::BadRequest().into()
}
fn main() {
let resp = TestRequest::with_header("content-type", "text/plain")
let resp = test::TestRequest::with_header("content-type", "text/plain")
.run(index)
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(resp.status(), http::StatusCode::OK);
let resp = TestRequest::default()
let resp = test::TestRequest::default()
.run(index)
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
assert_eq!(resp.status(), http::StatusCode::BAD_REQUEST);
}
```
@ -55,11 +52,11 @@ for more information.
```rust
# extern crate actix_web;
use actix_web::*;
use actix_web::{HttpRequest, HttpResponse, HttpMessage};
use actix_web::test::TestServer;
fn index(req: HttpRequest) -> HttpResponse {
httpcodes::HttpOk.into()
HttpResponse::Ok().into()
}
fn main() {
@ -77,14 +74,11 @@ The other option is to use an application factory. In this case you need to pass
function same way as you would for real http server configuration.
```rust
# extern crate http;
# extern crate actix_web;
use http::Method;
use actix_web::*;
use actix_web::test::TestServer;
use actix_web::{http, test, Application, HttpRequest, HttpResponse};
fn index(req: HttpRequest) -> HttpResponse {
httpcodes::HttpOk.into()
HttpResponse::Ok().into()
}
/// This function get called by http server.
@ -94,9 +88,10 @@ fn create_app() -> Application {
}
fn main() {
let mut srv = TestServer::with_factory(create_app); // <- Start new test server
let mut srv = test::TestServer::with_factory(create_app); // <- Start new test server
let request = srv.client(Method::GET, "/test").finish().unwrap(); // <- create client request
let request = srv.client(
http::Method::GET, "/test").finish().unwrap(); // <- create client request
let response = srv.execute(request.send()).unwrap(); // <- send request to the server
assert!(response.status().is_success()); // <- check response

View File

@ -178,14 +178,14 @@ impl<S> Application<S> where S: 'static {
///
/// ```rust
/// # extern crate actix_web;
/// use actix_web::{Application, http, httpcodes};
/// use actix_web::{http, Application, HttpResponse};
///
/// fn main() {
/// let app = Application::new()
/// .prefix("/app")
/// .resource("/test", |r| {
/// r.method(http::Method::GET).f(|_| httpcodes::HttpOk);
/// r.method(http::Method::HEAD).f(|_| httpcodes::HttpMethodNotAllowed);
/// r.method(http::Method::GET).f(|_| HttpResponse::Ok());
/// r.method(http::Method::HEAD).f(|_| HttpResponse::MethodNotAllowed());
/// })
/// .finish();
/// }
@ -222,13 +222,13 @@ impl<S> Application<S> where S: 'static {
///
/// ```rust
/// # extern crate actix_web;
/// use actix_web::{Application, http, httpcodes};
/// use actix_web::{http, Application, HttpResponse};
///
/// fn main() {
/// let app = Application::new()
/// .resource("/test", |r| {
/// r.method(http::Method::GET).f(|_| httpcodes::HttpOk);
/// r.method(http::Method::HEAD).f(|_| httpcodes::HttpMethodNotAllowed);
/// r.method(http::Method::GET).f(|_| HttpResponse::Ok());
/// r.method(http::Method::HEAD).f(|_| HttpResponse::MethodNotAllowed());
/// });
/// }
/// ```
@ -277,12 +277,12 @@ impl<S> Application<S> where S: 'static {
///
/// ```rust
/// # extern crate actix_web;
/// use actix_web::{Application, HttpRequest, HttpResponse, Result, httpcodes};
/// use actix_web::{Application, HttpRequest, HttpResponse, Result};
///
/// fn index(mut req: HttpRequest) -> Result<HttpResponse> {
/// let url = req.url_for("youtube", &["oHg5SJYRHA0"])?;
/// assert_eq!(url.as_str(), "https://youtube.com/watch/oHg5SJYRHA0");
/// Ok(httpcodes::HttpOk.into())
/// Ok(HttpResponse::Ok().into())
/// }
///
/// fn main() {
@ -315,15 +315,15 @@ impl<S> Application<S> where S: 'static {
///
/// ```rust
/// # extern crate actix_web;
/// use actix_web::{Application, HttpRequest, http, httpcodes};
/// use actix_web::{http, Application, HttpRequest, HttpResponse};
///
/// fn main() {
/// let app = Application::new()
/// .handler("/app", |req: HttpRequest| {
/// match *req.method() {
/// http::Method::GET => httpcodes::HttpOk,
/// http::Method::POST => httpcodes::HttpMethodNotAllowed,
/// _ => httpcodes::HttpNotFound,
/// http::Method::GET => HttpResponse::Ok(),
/// http::Method::POST => HttpResponse::MethodNotAllowed(),
/// _ => HttpResponse::NotFound(),
/// }});
/// }
/// ```
@ -352,14 +352,14 @@ impl<S> Application<S> where S: 'static {
///
/// ```rust
/// # extern crate actix_web;
/// use actix_web::{Application, http, httpcodes, fs, middleware};
/// use actix_web::{Application, HttpResponse, http, fs, middleware};
///
/// // this function could be located in different module
/// fn config(app: Application) -> Application {
/// app
/// .resource("/test", |r| {
/// r.method(http::Method::GET).f(|_| httpcodes::HttpOk);
/// r.method(http::Method::HEAD).f(|_| httpcodes::HttpMethodNotAllowed);
/// r.method(http::Method::GET).f(|_| HttpResponse::Ok());
/// r.method(http::Method::HEAD).f(|_| HttpResponse::MethodNotAllowed());
/// })
/// }
///
@ -427,11 +427,11 @@ impl<S> Application<S> where S: 'static {
/// HttpServer::new(|| { vec![
/// Application::with_state(State1)
/// .prefix("/app1")
/// .resource("/", |r| r.h(httpcodes::HttpOk))
/// .resource("/", |r| r.f(|r| HttpResponse::Ok()))
/// .boxed(),
/// Application::with_state(State2)
/// .prefix("/app2")
/// .resource("/", |r| r.h(httpcodes::HttpOk))
/// .resource("/", |r| r.f(|r| HttpResponse::Ok()))
/// .boxed() ]})
/// .bind("127.0.0.1:8080").unwrap()
/// .run()
@ -487,12 +487,12 @@ mod tests {
use super::*;
use test::TestRequest;
use httprequest::HttpRequest;
use httpcodes;
use httpresponse::HttpResponse;
#[test]
fn test_default_resource() {
let mut app = Application::new()
.resource("/test", |r| r.h(httpcodes::HttpOk))
.resource("/test", |r| r.f(|_| HttpResponse::Ok()))
.finish();
let req = TestRequest::with_uri("/test").finish();
@ -504,7 +504,7 @@ mod tests {
assert_eq!(resp.as_response().unwrap().status(), StatusCode::NOT_FOUND);
let mut app = Application::new()
.default_resource(|r| r.h(httpcodes::HttpMethodNotAllowed))
.default_resource(|r| r.f(|_| HttpResponse::MethodNotAllowed()))
.finish();
let req = TestRequest::with_uri("/blah").finish();
let resp = app.run(req);
@ -515,7 +515,7 @@ mod tests {
fn test_unhandled_prefix() {
let mut app = Application::new()
.prefix("/test")
.resource("/test", |r| r.h(httpcodes::HttpOk))
.resource("/test", |r| r.f(|_| HttpResponse::Ok()))
.finish();
assert!(app.handle(HttpRequest::default()).is_err());
}
@ -523,7 +523,7 @@ mod tests {
#[test]
fn test_state() {
let mut app = Application::with_state(10)
.resource("/", |r| r.h(httpcodes::HttpOk))
.resource("/", |r| r.f(|_| HttpResponse::Ok()))
.finish();
let req = HttpRequest::default().with_state(Rc::clone(&app.state), app.router.clone());
let resp = app.run(req);
@ -534,7 +534,7 @@ mod tests {
fn test_prefix() {
let mut app = Application::new()
.prefix("/test")
.resource("/blah", |r| r.h(httpcodes::HttpOk))
.resource("/blah", |r| r.f(|_| HttpResponse::Ok()))
.finish();
let req = TestRequest::with_uri("/test").finish();
let resp = app.handle(req);
@ -556,7 +556,7 @@ mod tests {
#[test]
fn test_handler() {
let mut app = Application::new()
.handler("/test", httpcodes::HttpOk)
.handler("/test", |_| HttpResponse::Ok())
.finish();
let req = TestRequest::with_uri("/test").finish();
@ -584,7 +584,7 @@ mod tests {
fn test_handler_prefix() {
let mut app = Application::new()
.prefix("/app")
.handler("/test", httpcodes::HttpOk)
.handler("/test", |_| HttpResponse::Ok())
.finish();
let req = TestRequest::with_uri("/test").finish();

View File

@ -13,10 +13,8 @@ pub use self::connector::{Connect, Connection, ClientConnector, ClientConnectorE
pub(crate) use self::writer::HttpClientWriter;
pub(crate) use self::parser::{HttpResponseParser, HttpResponseParserError};
use httpcodes;
use httpresponse::HttpResponse;
use error::ResponseError;
use httpresponse::HttpResponse;
/// Convert `SendRequestError` to a `HttpResponse`
@ -24,8 +22,9 @@ impl ResponseError for SendRequestError {
fn error_response(&self) -> HttpResponse {
match *self {
SendRequestError::Connector(_) => httpcodes::HttpBadGateway.into(),
_ => httpcodes::HttpInternalServerError.into(),
}
SendRequestError::Connector(_) => HttpResponse::BadGateway(),
_ => HttpResponse::InternalServerError(),
}
.into()
}
}

View File

@ -20,11 +20,9 @@ pub use url::ParseError as UrlParseError;
// re-exports
pub use cookie::{ParseError as CookieParseError};
use body::Body;
use handler::Responder;
use httprequest::HttpRequest;
use httpresponse::HttpResponse;
use httpcodes::{self, HttpExpectationFailed};
/// A specialized [`Result`](https://doc.rust-lang.org/std/result/enum.Result.html)
/// for actix web operations
@ -55,7 +53,7 @@ pub trait ResponseError: Fail {
///
/// Internal server error is generated by default.
fn error_response(&self) -> HttpResponse {
HttpResponse::new(StatusCode::INTERNAL_SERVER_ERROR, Body::Empty)
HttpResponse::new(StatusCode::INTERNAL_SERVER_ERROR)
}
}
@ -113,7 +111,7 @@ impl ResponseError for UrlParseError {}
/// Return `BAD_REQUEST` for `de::value::Error`
impl ResponseError for DeError {
fn error_response(&self) -> HttpResponse {
HttpResponse::new(StatusCode::BAD_REQUEST, Body::Empty)
HttpResponse::new(StatusCode::BAD_REQUEST)
}
}
@ -127,11 +125,11 @@ impl ResponseError for io::Error {
fn error_response(&self) -> HttpResponse {
match self.kind() {
io::ErrorKind::NotFound =>
HttpResponse::new(StatusCode::NOT_FOUND, Body::Empty),
HttpResponse::new(StatusCode::NOT_FOUND),
io::ErrorKind::PermissionDenied =>
HttpResponse::new(StatusCode::FORBIDDEN, Body::Empty),
HttpResponse::new(StatusCode::FORBIDDEN),
_ =>
HttpResponse::new(StatusCode::INTERNAL_SERVER_ERROR, Body::Empty)
HttpResponse::new(StatusCode::INTERNAL_SERVER_ERROR)
}
}
}
@ -139,14 +137,14 @@ impl ResponseError for io::Error {
/// `BadRequest` for `InvalidHeaderValue`
impl ResponseError for header::InvalidHeaderValue {
fn error_response(&self) -> HttpResponse {
HttpResponse::new(StatusCode::BAD_REQUEST, Body::Empty)
HttpResponse::new(StatusCode::BAD_REQUEST)
}
}
/// `BadRequest` for `InvalidHeaderValue`
impl ResponseError for header::InvalidHeaderValueBytes {
fn error_response(&self) -> HttpResponse {
HttpResponse::new(StatusCode::BAD_REQUEST, Body::Empty)
HttpResponse::new(StatusCode::BAD_REQUEST)
}
}
@ -195,7 +193,7 @@ pub enum ParseError {
/// Return `BadRequest` for `ParseError`
impl ResponseError for ParseError {
fn error_response(&self) -> HttpResponse {
HttpResponse::new(StatusCode::BAD_REQUEST, Body::Empty)
HttpResponse::new(StatusCode::BAD_REQUEST)
}
}
@ -270,7 +268,7 @@ impl ResponseError for PayloadError {}
/// Return `BadRequest` for `cookie::ParseError`
impl ResponseError for cookie::ParseError {
fn error_response(&self) -> HttpResponse {
HttpResponse::new(StatusCode::BAD_REQUEST, Body::Empty)
HttpResponse::new(StatusCode::BAD_REQUEST)
}
}
@ -290,8 +288,8 @@ pub enum HttpRangeError {
/// Return `BadRequest` for `HttpRangeError`
impl ResponseError for HttpRangeError {
fn error_response(&self) -> HttpResponse {
HttpResponse::new(
StatusCode::BAD_REQUEST, Body::from("Invalid Range header provided"))
HttpResponse::with_body(
StatusCode::BAD_REQUEST, "Invalid Range header provided")
}
}
@ -343,7 +341,7 @@ impl From<PayloadError> for MultipartError {
impl ResponseError for MultipartError {
fn error_response(&self) -> HttpResponse {
HttpResponse::new(StatusCode::BAD_REQUEST, Body::Empty)
HttpResponse::new(StatusCode::BAD_REQUEST)
}
}
@ -360,7 +358,7 @@ pub enum ExpectError {
impl ResponseError for ExpectError {
fn error_response(&self) -> HttpResponse {
HttpExpectationFailed.with_body("Unknown Expect")
HttpResponse::with_body(StatusCode::EXPECTATION_FAILED, "Unknown Expect")
}
}
@ -378,7 +376,7 @@ pub enum ContentTypeError {
/// Return `BadRequest` for `ContentTypeError`
impl ResponseError for ContentTypeError {
fn error_response(&self) -> HttpResponse {
HttpResponse::new(StatusCode::BAD_REQUEST, Body::Empty)
HttpResponse::new(StatusCode::BAD_REQUEST)
}
}
@ -410,9 +408,12 @@ impl ResponseError for UrlencodedError {
fn error_response(&self) -> HttpResponse {
match *self {
UrlencodedError::Overflow => httpcodes::HttpPayloadTooLarge.into(),
UrlencodedError::UnknownLength => httpcodes::HttpLengthRequired.into(),
_ => httpcodes::HttpBadRequest.into(),
UrlencodedError::Overflow =>
HttpResponse::new(StatusCode::PAYLOAD_TOO_LARGE),
UrlencodedError::UnknownLength =>
HttpResponse::new(StatusCode::LENGTH_REQUIRED),
_ =>
HttpResponse::new(StatusCode::BAD_REQUEST),
}
}
}
@ -445,8 +446,10 @@ impl ResponseError for JsonPayloadError {
fn error_response(&self) -> HttpResponse {
match *self {
JsonPayloadError::Overflow => httpcodes::HttpPayloadTooLarge.into(),
_ => httpcodes::HttpBadRequest.into(),
JsonPayloadError::Overflow =>
HttpResponse::new(StatusCode::PAYLOAD_TOO_LARGE),
_ =>
HttpResponse::new(StatusCode::BAD_REQUEST),
}
}
}
@ -482,7 +485,7 @@ pub enum UriSegmentError {
impl ResponseError for UriSegmentError {
fn error_response(&self) -> HttpResponse {
HttpResponse::new(StatusCode::BAD_REQUEST, Body::Empty)
HttpResponse::new(StatusCode::BAD_REQUEST)
}
}
@ -571,7 +574,7 @@ impl<T> ResponseError for InternalError<T>
where T: Send + Sync + fmt::Debug + 'static
{
fn error_response(&self) -> HttpResponse {
HttpResponse::new(self.status, Body::Empty)
HttpResponse::new(self.status)
}
}

View File

@ -13,7 +13,6 @@ use std::time::{SystemTime, UNIX_EPOCH};
use std::os::unix::fs::MetadataExt;
use bytes::{Bytes, BytesMut, BufMut};
use http::{Method, StatusCode};
use futures::{Async, Poll, Future, Stream};
use futures_cpupool::{CpuPool, CpuFuture};
use mime_guess::get_mime_type;
@ -22,10 +21,10 @@ use header;
use error::Error;
use param::FromParam;
use handler::{Handler, RouteHandler, WrapHandler, Responder, Reply};
use http::{Method, StatusCode};
use httpmessage::HttpMessage;
use httprequest::HttpRequest;
use httpresponse::HttpResponse;
use httpcodes::{HttpOk, HttpFound, HttpNotFound, HttpMethodNotAllowed};
/// A file with an associated name; responds with the Content-Type based on the
/// file extension.
@ -177,10 +176,10 @@ impl Responder for NamedFile {
fn respond_to(self, req: HttpRequest) -> Result<HttpResponse, io::Error> {
if self.only_get && *req.method() != Method::GET && *req.method() != Method::HEAD {
return Ok(HttpMethodNotAllowed.build()
return Ok(HttpResponse::MethodNotAllowed()
.header(header::CONTENT_TYPE, "text/plain")
.header(header::ALLOW, "GET, HEAD")
.body("This resource only supports GET and HEAD.").unwrap())
.body("This resource only supports GET and HEAD."))
}
let etag = self.etag();
@ -208,7 +207,7 @@ impl Responder for NamedFile {
false
};
let mut resp = HttpOk.build();
let mut resp = HttpResponse::Ok();
resp
.if_some(self.path().extension(), |ext, resp| {
@ -218,13 +217,13 @@ impl Responder for NamedFile {
.if_some(etag, |etag, resp| {resp.set(header::ETag(etag));});
if precondition_failed {
return Ok(resp.status(StatusCode::PRECONDITION_FAILED).finish().unwrap())
return Ok(resp.status(StatusCode::PRECONDITION_FAILED).finish())
} else if not_modified {
return Ok(resp.status(StatusCode::NOT_MODIFIED).finish().unwrap())
return Ok(resp.status(StatusCode::NOT_MODIFIED).finish())
}
if *req.method() == Method::HEAD {
Ok(resp.finish().unwrap())
Ok(resp.finish())
} else {
let reader = ChunkedReadFile {
size: self.md.len(),
@ -233,7 +232,7 @@ impl Responder for NamedFile {
file: Some(self.file),
fut: None,
};
Ok(resp.streaming(reader).unwrap())
Ok(resp.streaming(reader))
}
}
}
@ -356,9 +355,9 @@ impl Responder for Directory {
<ul>\
{}\
</ul></body>\n</html>", index_of, index_of, body);
Ok(HttpOk.build()
Ok(HttpResponse::Ok()
.content_type("text/html; charset=utf-8")
.body(html).unwrap())
.body(html))
}
}
@ -418,7 +417,8 @@ impl<S: 'static> StaticFiles<S> {
index: None,
show_index: index,
cpu_pool: CpuPool::new(40),
default: Box::new(WrapHandler::new(|_| HttpNotFound)),
default: Box::new(WrapHandler::new(
|_| HttpResponse::new(StatusCode::NOT_FOUND))),
_chunk_size: 0,
_follow_symlinks: false,
}
@ -465,9 +465,9 @@ impl<S: 'static> Handler<S> for StaticFiles<S> {
new_path.push('/');
}
new_path.push_str(redir_index);
HttpFound.build()
HttpResponse::Found()
.header(header::LOCATION, new_path.as_str())
.finish().unwrap()
.finish()
.respond_to(req.without_state())
} else if self.show_index {
Directory::new(self.directory.clone(), path)

View File

@ -47,9 +47,8 @@ pub trait FromRequest<S>: Sized where S: 'static
/// # extern crate actix_web;
/// # extern crate futures;
/// # use futures::future::Future;
/// use actix_web::AsyncResponder;
/// use futures::future::result;
/// use actix_web::{Either, Error, HttpRequest, HttpResponse, httpcodes};
/// use actix_web::{Either, Error, HttpRequest, HttpResponse, AsyncResponder};
///
/// type RegisterResult = Either<HttpResponse, Box<Future<Item=HttpResponse, Error=Error>>>;
///
@ -57,13 +56,13 @@ pub trait FromRequest<S>: Sized where S: 'static
/// fn index(req: HttpRequest) -> RegisterResult {
/// if is_a_variant() { // <- choose variant A
/// Either::A(
/// httpcodes::HttpBadRequest.with_body("Bad data"))
/// HttpResponse::BadRequest().body("Bad data"))
/// } else {
/// Either::B( // <- variant B
/// result(HttpResponse::Ok()
/// result(Ok(HttpResponse::Ok()
/// .content_type("text/html")
/// .body(format!("Hello!"))
/// .map_err(|e| e.into())).responder())
/// .body("Hello!")))
/// .responder())
/// }
/// }
/// # fn is_a_variant() -> bool { true }
@ -105,8 +104,9 @@ impl<A, B> Responder for Either<A, B>
/// # extern crate actix_web;
/// # extern crate futures;
/// # #[macro_use] extern crate serde_derive;
/// use actix_web::*;
/// use futures::future::Future;
/// use actix_web::{
/// Application, HttpRequest, HttpResponse, HttpMessage, Error, AsyncResponder};
///
/// #[derive(Deserialize, Debug)]
/// struct MyObj {
@ -117,7 +117,7 @@ impl<A, B> Responder for Either<A, B>
/// req.json() // <- get JsonBody future
/// .from_err()
/// .and_then(|val: MyObj| { // <- deserialized value
/// Ok(httpcodes::HttpOk.into())
/// Ok(HttpResponse::Ok().into())
/// })
/// // Construct boxed future by using `AsyncResponder::responder()` method
/// .responder()

View File

@ -32,11 +32,11 @@ header! {
/// ```rust
/// # extern crate actix_web;
/// extern crate mime;
/// use actix_web::httpcodes::HttpOk;
/// use actix_web::HttpResponse;
/// use actix_web::http::header::{Accept, qitem};
///
/// # fn main() {
/// let mut builder = HttpOk.build();
/// let mut builder = HttpResponse::Ok();
///
/// builder.set(
/// Accept(vec![
@ -49,11 +49,11 @@ header! {
/// ```rust
/// # extern crate actix_web;
/// extern crate mime;
/// use actix_web::httpcodes::HttpOk;
/// use actix_web::HttpResponse;
/// use actix_web::http::header::{Accept, qitem};
///
/// # fn main() {
/// let mut builder = HttpOk.build();
/// let mut builder = HttpResponse::Ok();
///
/// builder.set(
/// Accept(vec![
@ -66,11 +66,11 @@ header! {
/// ```rust
/// # extern crate actix_web;
/// extern crate mime;
/// use actix_web::httpcodes::HttpOk;
/// use actix_web::HttpResponse;
/// use actix_web::http::header::{Accept, QualityItem, q, qitem};
///
/// # fn main() {
/// let mut builder = HttpOk.build();
/// let mut builder = HttpResponse::Ok();
///
/// builder.set(
/// Accept(vec![

View File

@ -23,11 +23,11 @@ header! {
/// # Examples
/// ```rust
/// # extern crate actix_web;
/// use actix_web::httpcodes::HttpOk;
/// use actix_web::HttpResponse;
/// use actix_web::http::header::{AcceptCharset, Charset, qitem};
///
/// # fn main() {
/// let mut builder = HttpOk.build();
/// let mut builder = HttpResponse::Ok();
/// builder.set(
/// AcceptCharset(vec![qitem(Charset::Us_Ascii)])
/// );
@ -35,11 +35,11 @@ header! {
/// ```
/// ```rust
/// # extern crate actix_web;
/// use actix_web::httpcodes::HttpOk;
/// use actix_web::HttpResponse;
/// use actix_web::http::header::{AcceptCharset, Charset, q, QualityItem};
///
/// # fn main() {
/// let mut builder = HttpOk.build();
/// let mut builder = HttpResponse::Ok();
/// builder.set(
/// AcceptCharset(vec![
/// QualityItem::new(Charset::Us_Ascii, q(900)),
@ -50,11 +50,11 @@ header! {
/// ```
/// ```rust
/// # extern crate actix_web;
/// use actix_web::httpcodes::HttpOk;
/// use actix_web::HttpResponse;
/// use actix_web::http::header::{AcceptCharset, Charset, qitem};
///
/// # fn main() {
/// let mut builder = HttpOk.build();
/// let mut builder = HttpResponse::Ok();
/// builder.set(
/// AcceptCharset(vec![qitem(Charset::Ext("utf-8".to_owned()))])
/// );

View File

@ -1,7 +1,6 @@
use language_tags::LanguageTag;
use header::{ACCEPT_LANGUAGE, QualityItem};
header! {
/// `Accept-Language` header, defined in
/// [RFC7231](http://tools.ietf.org/html/rfc7231#section-5.3.5)
@ -26,11 +25,11 @@ header! {
/// ```rust
/// # extern crate actix_web;
/// # extern crate language_tags;
/// use actix_web::httpcodes::HttpOk;
/// use actix_web::HttpResponse;
/// use actix_web::http::header::{AcceptLanguage, LanguageTag, qitem};
///
/// # fn main() {
/// let mut builder = HttpOk.build();
/// let mut builder = HttpResponse::Ok();
/// let mut langtag: LanguageTag = Default::default();
/// langtag.language = Some("en".to_owned());
/// langtag.region = Some("US".to_owned());
@ -45,11 +44,11 @@ header! {
/// ```rust
/// # extern crate actix_web;
/// # #[macro_use] extern crate language_tags;
/// use actix_web::httpcodes::HttpOk;
/// use actix_web::HttpResponse;
/// use actix_web::http::header::{AcceptLanguage, QualityItem, q, qitem};
/// #
/// # fn main() {
/// let mut builder = HttpOk.build();
/// let mut builder = HttpResponse::Ok();
/// builder.set(
/// AcceptLanguage(vec![
/// qitem(langtag!(da)),

View File

@ -25,12 +25,12 @@ header! {
/// ```rust
/// # extern crate http;
/// # extern crate actix_web;
/// use actix_web::httpcodes::HttpOk;
/// use actix_web::HttpResponse;
/// use actix_web::http::header::Allow;
/// use http::Method;
///
/// # fn main() {
/// let mut builder = HttpOk.build();
/// let mut builder = HttpResponse::Ok();
/// builder.set(
/// Allow(vec![Method::GET])
/// );
@ -40,12 +40,12 @@ header! {
/// ```rust
/// # extern crate http;
/// # extern crate actix_web;
/// use actix_web::httpcodes::HttpOk;
/// use actix_web::HttpResponse;
/// use actix_web::http::header::Allow;
/// use http::Method;
///
/// # fn main() {
/// let mut builder = HttpOk.build();
/// let mut builder = HttpResponse::Ok();
/// builder.set(
/// Allow(vec![
/// Method::GET,

View File

@ -26,20 +26,20 @@ use header::{from_comma_delimited, fmt_comma_delimited};
///
/// # Examples
/// ```rust
/// use actix_web::httpcodes::HttpOk;
/// use actix_web::HttpResponse;
/// use actix_web::http::header::{CacheControl, CacheDirective};
///
/// let mut builder = HttpOk.build();
/// let mut builder = HttpResponse::Ok();
/// builder.set(
/// CacheControl(vec![CacheDirective::MaxAge(86400u32)])
/// );
/// ```
///
/// ```rust
/// use actix_web::httpcodes::HttpOk;
/// use actix_web::HttpResponse;
/// use actix_web::http::header::{CacheControl, CacheDirective};
///
/// let mut builder = HttpOk.build();
/// let mut builder = HttpResponse::Ok();
/// builder.set(
/// CacheControl(vec![
/// CacheDirective::NoCache,

View File

@ -1,7 +1,6 @@
use language_tags::LanguageTag;
use header::{CONTENT_LANGUAGE, QualityItem};
header! {
/// `Content-Language` header, defined in
/// [RFC7231](https://tools.ietf.org/html/rfc7231#section-3.1.3.2)
@ -27,11 +26,11 @@ header! {
/// ```rust
/// # extern crate actix_web;
/// # #[macro_use] extern crate language_tags;
/// use actix_web::httpcodes::HttpOk;
/// use actix_web::HttpResponse;
/// # use actix_web::http::header::{ContentLanguage, qitem};
/// #
/// # fn main() {
/// let mut builder = HttpOk.build();
/// let mut builder = HttpResponse::Ok();
/// builder.set(
/// ContentLanguage(vec![
/// qitem(langtag!(en)),
@ -43,12 +42,12 @@ header! {
/// ```rust
/// # extern crate actix_web;
/// # #[macro_use] extern crate language_tags;
/// use actix_web::httpcodes::HttpOk;
/// use actix_web::HttpResponse;
/// # use actix_web::http::header::{ContentLanguage, qitem};
/// #
/// # fn main() {
///
/// let mut builder = HttpOk.build();
/// let mut builder = HttpResponse::Ok();
/// builder.set(
/// ContentLanguage(vec![
/// qitem(langtag!(da)),

View File

@ -4,7 +4,6 @@ use error::ParseError;
use header::{IntoHeaderValue, Writer,
HeaderValue, InvalidHeaderValueBytes, CONTENT_RANGE};
header! {
/// `Content-Range` header, defined in
/// [RFC7233](http://tools.ietf.org/html/rfc7233#section-4.2)

View File

@ -32,11 +32,11 @@ header! {
/// # Examples
///
/// ```rust
/// use actix_web::httpcodes::HttpOk;
/// use actix_web::HttpResponse;
/// use actix_web::http::header::ContentType;
///
/// # fn main() {
/// let mut builder = HttpOk.build();
/// let mut builder = HttpResponse::Ok();
/// builder.set(
/// ContentType::json()
/// );
@ -47,11 +47,11 @@ header! {
/// # extern crate mime;
/// # extern crate actix_web;
/// use mime::TEXT_HTML;
/// use actix_web::httpcodes::HttpOk;
/// use actix_web::HttpResponse;
/// use actix_web::http::header::ContentType;
///
/// # fn main() {
/// let mut builder = HttpOk.build();
/// let mut builder = HttpResponse::Ok();
/// builder.set(
/// ContentType(TEXT_HTML)
/// );

View File

@ -21,11 +21,11 @@ header! {
/// # Example
///
/// ```rust
/// use actix_web::httpcodes;
/// use actix_web::HttpResponse;
/// use actix_web::http::header::Date;
/// use std::time::SystemTime;
///
/// let mut builder = httpcodes::HttpOk.build();
/// let mut builder = HttpResponse::Ok();
/// builder.set(Date(SystemTime::now().into()));
/// ```
(Date, DATE) => [HttpDate]

View File

@ -28,18 +28,18 @@ header! {
/// # Examples
///
/// ```rust
/// use actix_web::httpcodes;
/// use actix_web::HttpResponse;
/// use actix_web::http::header::{ETag, EntityTag};
///
/// let mut builder = httpcodes::HttpOk.build();
/// let mut builder = HttpResponse::Ok();
/// builder.set(ETag(EntityTag::new(false, "xyzzy".to_owned())));
/// ```
///
/// ```rust
/// use actix_web::httpcodes;
/// use actix_web::HttpResponse;
/// use actix_web::http::header::{ETag, EntityTag};
///
/// let mut builder = httpcodes::HttpOk.build();
/// let mut builder = HttpResponse::Ok();
/// builder.set(ETag(EntityTag::new(true, "xyzzy".to_owned())));
/// ```
(ETag, ETAG) => [EntityTag]

View File

@ -22,11 +22,11 @@ header! {
/// # Example
///
/// ```rust
/// use actix_web::httpcodes;
/// use actix_web::HttpResponse;
/// use actix_web::http::header::Expires;
/// use std::time::{SystemTime, Duration};
///
/// let mut builder = httpcodes::HttpOk.build();
/// let mut builder = HttpResponse::Ok();
/// let expiration = SystemTime::now() + Duration::from_secs(60 * 60 * 24);
/// builder.set(Expires(expiration.into()));
/// ```

View File

@ -30,18 +30,18 @@ header! {
/// # Examples
///
/// ```rust
/// use actix_web::httpcodes;
/// use actix_web::HttpResponse;
/// use actix_web::http::header::IfMatch;
///
/// let mut builder = httpcodes::HttpOk.build();
/// let mut builder = HttpResponse::Ok();
/// builder.set(IfMatch::Any);
/// ```
///
/// ```rust
/// use actix_web::httpcodes;
/// use actix_web::HttpResponse;
/// use actix_web::http::header::{IfMatch, EntityTag};
///
/// let mut builder = httpcodes::HttpOk.build();
/// let mut builder = HttpResponse::Ok();
/// builder.set(
/// IfMatch::Items(vec![
/// EntityTag::new(false, "xyzzy".to_owned()),

View File

@ -22,11 +22,11 @@ header! {
/// # Example
///
/// ```rust
/// use actix_web::httpcodes;
/// use actix_web::HttpResponse;
/// use actix_web::http::header::IfModifiedSince;
/// use std::time::{SystemTime, Duration};
///
/// let mut builder = httpcodes::HttpOk.build();
/// let mut builder = HttpResponse::Ok();
/// let modified = SystemTime::now() - Duration::from_secs(60 * 60 * 24);
/// builder.set(IfModifiedSince(modified.into()));
/// ```

View File

@ -32,18 +32,18 @@ header! {
/// # Examples
///
/// ```rust
/// use actix_web::httpcodes;
/// use actix_web::HttpResponse;
/// use actix_web::http::header::IfNoneMatch;
///
/// let mut builder = httpcodes::HttpOk.build();
/// let mut builder = HttpResponse::Ok();
/// builder.set(IfNoneMatch::Any);
/// ```
///
/// ```rust
/// use actix_web::httpcodes;
/// use actix_web::HttpResponse;
/// use actix_web::http::header::{IfNoneMatch, EntityTag};
///
/// let mut builder = httpcodes::HttpOk.build();
/// let mut builder = HttpResponse::Ok();
/// builder.set(
/// IfNoneMatch::Items(vec![
/// EntityTag::new(false, "xyzzy".to_owned()),

View File

@ -35,19 +35,19 @@ use header::{IntoHeaderValue, Header, HeaderName, HeaderValue,
/// # Examples
///
/// ```rust
/// use actix_web::httpcodes;
/// use actix_web::HttpResponse;
/// use actix_web::http::header::{IfRange, EntityTag};
///
/// let mut builder = httpcodes::HttpOk.build();
/// let mut builder = HttpResponse::Ok();
/// builder.set(IfRange::EntityTag(EntityTag::new(false, "xyzzy".to_owned())));
/// ```
///
/// ```rust
/// use actix_web::httpcodes;
/// use actix_web::HttpResponse;
/// use actix_web::http::header::IfRange;
/// use std::time::{SystemTime, Duration};
///
/// let mut builder = httpcodes::HttpOk.build();
/// let mut builder = HttpResponse::Ok();
/// let fetched = SystemTime::now() - Duration::from_secs(60 * 60 * 24);
/// builder.set(IfRange::Date(fetched.into()));
/// ```

View File

@ -23,11 +23,11 @@ header! {
/// # Example
///
/// ```rust
/// use actix_web::httpcodes;
/// use actix_web::HttpResponse;
/// use actix_web::http::header::IfUnmodifiedSince;
/// use std::time::{SystemTime, Duration};
///
/// let mut builder = httpcodes::HttpOk.build();
/// let mut builder = HttpResponse::Ok();
/// let modified = SystemTime::now() - Duration::from_secs(60 * 60 * 24);
/// builder.set(IfUnmodifiedSince(modified.into()));
/// ```

View File

@ -22,11 +22,11 @@ header! {
/// # Example
///
/// ```rust
/// use actix_web::httpcodes;
/// use actix_web::HttpResponse;
/// use actix_web::http::header::LastModified;
/// use std::time::{SystemTime, Duration};
///
/// let mut builder = httpcodes::HttpOk.build();
/// let mut builder = HttpResponse::Ok();
/// let modified = SystemTime::now() - Duration::from_secs(60 * 60 * 24);
/// builder.set(LastModified(modified.into()));
/// ```

View File

@ -9,7 +9,6 @@ use modhttp::{Error as HttpError};
use modhttp::header::GetAll;
use mime::Mime;
#[doc(hidden)]
pub use modhttp::header::*;
use error::ParseError;

View File

@ -3,8 +3,6 @@
use regex::Regex;
use http::{header, StatusCode};
use body::Body;
use error::Error;
use handler::Handler;
use httprequest::HttpRequest;
use httpresponse::HttpResponse;
@ -36,8 +34,8 @@ use httpresponse::HttpResponse;
/// # use actix_web::*;
/// use actix_web::http::NormalizePath;
///
/// # fn index(req: HttpRequest) -> httpcodes::StaticResponse {
/// # httpcodes::HttpOk
/// # fn index(req: HttpRequest) -> HttpResponse {
/// # HttpResponse::Ok().into()
/// # }
/// fn main() {
/// let app = Application::new()
@ -83,7 +81,7 @@ impl NormalizePath {
}
impl<S> Handler<S> for NormalizePath {
type Result = Result<HttpResponse, Error>;
type Result = HttpResponse;
fn handle(&mut self, req: HttpRequest<S>) -> Self::Result {
if let Some(router) = req.router() {
@ -96,7 +94,7 @@ impl<S> Handler<S> for NormalizePath {
let p = if !query.is_empty() { p + "?" + query } else { p };
return HttpResponse::build(self.redirect)
.header(header::LOCATION, p.as_ref())
.body(Body::Empty);
.finish();
}
// merge slashes and append trailing slash
if self.append && !p.ends_with('/') {
@ -105,7 +103,7 @@ impl<S> Handler<S> for NormalizePath {
let p = if !query.is_empty() { p + "?" + query } else { p };
return HttpResponse::build(self.redirect)
.header(header::LOCATION, p.as_str())
.body(Body::Empty);
.finish()
}
}
@ -119,7 +117,7 @@ impl<S> Handler<S> for NormalizePath {
} else {
req.header(header::LOCATION, p)
}
.body(Body::Empty);
.finish();
}
}
} else if p.ends_with('/') {
@ -128,11 +126,12 @@ impl<S> Handler<S> for NormalizePath {
if router.has_route(p) {
let mut req = HttpResponse::build(self.redirect);
return if !query.is_empty() {
req.header(header::LOCATION, (p.to_owned() + "?" + query).as_str())
req.header(header::LOCATION,
(p.to_owned() + "?" + query).as_str())
} else {
req.header(header::LOCATION, p)
}
.body(Body::Empty);
.finish();
}
}
}
@ -143,11 +142,11 @@ impl<S> Handler<S> for NormalizePath {
let p = if !query.is_empty() { p + "?" + query } else { p };
return HttpResponse::build(self.redirect)
.header(header::LOCATION, p.as_str())
.body(Body::Empty);
.finish();
}
}
}
Ok(HttpResponse::new(self.not_found, Body::Empty))
HttpResponse::new(self.not_found)
}
}
@ -159,7 +158,7 @@ mod tests {
use application::Application;
fn index(_req: HttpRequest) -> HttpResponse {
HttpResponse::new(StatusCode::OK, Body::Empty)
HttpResponse::new(StatusCode::OK)
}
#[test]

View File

@ -1,5 +1,5 @@
//! Basic http responses
#![allow(non_upper_case_globals)]
#![allow(non_upper_case_globals, deprecated)]
use http::StatusCode;
use body::Body;
@ -8,70 +8,123 @@ use handler::{Reply, Handler, RouteHandler, Responder};
use httprequest::HttpRequest;
use httpresponse::{HttpResponse, HttpResponseBuilder};
#[deprecated(since="0.5.0", note="please use `HttpResponse::Ok()` instead")]
pub const HttpOk: StaticResponse = StaticResponse(StatusCode::OK);
#[deprecated(since="0.5.0", note="please use `HttpResponse::Created()` instead")]
pub const HttpCreated: StaticResponse = StaticResponse(StatusCode::CREATED);
#[deprecated(since="0.5.0", note="please use `HttpResponse::Accepted()` instead")]
pub const HttpAccepted: StaticResponse = StaticResponse(StatusCode::ACCEPTED);
#[deprecated(since="0.5.0",
note="please use `HttpResponse::pNonAuthoritativeInformation()` instead")]
pub const HttpNonAuthoritativeInformation: StaticResponse =
StaticResponse(StatusCode::NON_AUTHORITATIVE_INFORMATION);
#[deprecated(since="0.5.0", note="please use `HttpResponse::NoContent()` instead")]
pub const HttpNoContent: StaticResponse = StaticResponse(StatusCode::NO_CONTENT);
#[deprecated(since="0.5.0", note="please use `HttpResponse::ResetContent()` instead")]
pub const HttpResetContent: StaticResponse = StaticResponse(StatusCode::RESET_CONTENT);
#[deprecated(since="0.5.0", note="please use `HttpResponse::PartialContent()` instead")]
pub const HttpPartialContent: StaticResponse = StaticResponse(StatusCode::PARTIAL_CONTENT);
#[deprecated(since="0.5.0", note="please use `HttpResponse::MultiStatus()` instead")]
pub const HttpMultiStatus: StaticResponse = StaticResponse(StatusCode::MULTI_STATUS);
#[deprecated(since="0.5.0", note="please use `HttpResponse::AlreadyReported()` instead")]
pub const HttpAlreadyReported: StaticResponse = StaticResponse(StatusCode::ALREADY_REPORTED);
#[deprecated(since="0.5.0", note="please use `HttpResponse::MultipleChoices()` instead")]
pub const HttpMultipleChoices: StaticResponse = StaticResponse(StatusCode::MULTIPLE_CHOICES);
#[deprecated(since="0.5.0", note="please use `HttpResponse::MovedPermanently()` instead")]
pub const HttpMovedPermanently: StaticResponse = StaticResponse(StatusCode::MOVED_PERMANENTLY);
#[deprecated(since="0.5.0", note="please use `HttpResponse::Found()` instead")]
pub const HttpFound: StaticResponse = StaticResponse(StatusCode::FOUND);
#[deprecated(since="0.5.0", note="please use `HttpResponse::SeeOther()` instead")]
pub const HttpSeeOther: StaticResponse = StaticResponse(StatusCode::SEE_OTHER);
#[deprecated(since="0.5.0", note="please use `HttpResponse::NotModified()` instead")]
pub const HttpNotModified: StaticResponse = StaticResponse(StatusCode::NOT_MODIFIED);
#[deprecated(since="0.5.0", note="please use `HttpResponse::UseProxy()` instead")]
pub const HttpUseProxy: StaticResponse = StaticResponse(StatusCode::USE_PROXY);
#[deprecated(since="0.5.0", note="please use `HttpResponse::TemporaryRedirect()` instead")]
pub const HttpTemporaryRedirect: StaticResponse =
StaticResponse(StatusCode::TEMPORARY_REDIRECT);
#[deprecated(since="0.5.0", note="please use `HttpResponse::PermanentRedirect()` instead")]
pub const HttpPermanentRedirect: StaticResponse =
StaticResponse(StatusCode::PERMANENT_REDIRECT);
#[deprecated(since="0.5.0", note="please use `HttpResponse::BadRequest()` instead")]
pub const HttpBadRequest: StaticResponse = StaticResponse(StatusCode::BAD_REQUEST);
#[deprecated(since="0.5.0", note="please use `HttpResponse::Unauthorized()` instead")]
pub const HttpUnauthorized: StaticResponse = StaticResponse(StatusCode::UNAUTHORIZED);
#[deprecated(since="0.5.0", note="please use `HttpResponse::PaymentRequired()` instead")]
pub const HttpPaymentRequired: StaticResponse = StaticResponse(StatusCode::PAYMENT_REQUIRED);
#[deprecated(since="0.5.0", note="please use `HttpResponse::Forbidden()` instead")]
pub const HttpForbidden: StaticResponse = StaticResponse(StatusCode::FORBIDDEN);
#[deprecated(since="0.5.0", note="please use `HttpResponse::NotFound()` instead")]
pub const HttpNotFound: StaticResponse = StaticResponse(StatusCode::NOT_FOUND);
#[deprecated(since="0.5.0", note="please use `HttpResponse::MethodNotAllowed()` instead")]
pub const HttpMethodNotAllowed: StaticResponse =
StaticResponse(StatusCode::METHOD_NOT_ALLOWED);
#[deprecated(since="0.5.0", note="please use `HttpResponse::NotAcceptable()` instead")]
pub const HttpNotAcceptable: StaticResponse = StaticResponse(StatusCode::NOT_ACCEPTABLE);
#[deprecated(since="0.5.0",
note="please use `HttpResponse::ProxyAuthenticationRequired()` instead")]
pub const HttpProxyAuthenticationRequired: StaticResponse =
StaticResponse(StatusCode::PROXY_AUTHENTICATION_REQUIRED);
#[deprecated(since="0.5.0", note="please use `HttpResponse::RequestTimeout()` instead")]
pub const HttpRequestTimeout: StaticResponse = StaticResponse(StatusCode::REQUEST_TIMEOUT);
#[deprecated(since="0.5.0", note="please use `HttpResponse::Conflict()` instead")]
pub const HttpConflict: StaticResponse = StaticResponse(StatusCode::CONFLICT);
#[deprecated(since="0.5.0", note="please use `HttpResponse::Gone()` instead")]
pub const HttpGone: StaticResponse = StaticResponse(StatusCode::GONE);
#[deprecated(since="0.5.0", note="please use `HttpResponse::LengthRequired()` instead")]
pub const HttpLengthRequired: StaticResponse = StaticResponse(StatusCode::LENGTH_REQUIRED);
#[deprecated(since="0.5.0", note="please use `HttpResponse::PreconditionFailed()` instead")]
pub const HttpPreconditionFailed: StaticResponse =
StaticResponse(StatusCode::PRECONDITION_FAILED);
#[deprecated(since="0.5.0", note="please use `HttpResponse::PayloadTooLarge()` instead")]
pub const HttpPayloadTooLarge: StaticResponse = StaticResponse(StatusCode::PAYLOAD_TOO_LARGE);
#[deprecated(since="0.5.0", note="please use `HttpResponse::UriTooLong()` instead")]
pub const HttpUriTooLong: StaticResponse = StaticResponse(StatusCode::URI_TOO_LONG);
#[deprecated(since="0.5.0",
note="please use `HttpResponse::UnsupportedMediaType()` instead")]
pub const HttpUnsupportedMediaType: StaticResponse =
StaticResponse(StatusCode::UNSUPPORTED_MEDIA_TYPE);
#[deprecated(since="0.5.0",
note="please use `HttpResponse::RangeNotSatisfiable()` instead")]
pub const HttpRangeNotSatisfiable: StaticResponse =
StaticResponse(StatusCode::RANGE_NOT_SATISFIABLE);
#[deprecated(since="0.5.0", note="please use `HttpResponse::ExpectationFailed()` instead")]
pub const HttpExpectationFailed: StaticResponse =
StaticResponse(StatusCode::EXPECTATION_FAILED);
#[deprecated(since="0.5.0",
note="please use `HttpResponse::InternalServerError()` instead")]
pub const HttpInternalServerError: StaticResponse =
StaticResponse(StatusCode::INTERNAL_SERVER_ERROR);
#[deprecated(since="0.5.0", note="please use `HttpResponse::NotImplemented()` instead")]
pub const HttpNotImplemented: StaticResponse = StaticResponse(StatusCode::NOT_IMPLEMENTED);
#[deprecated(since="0.5.0", note="please use `HttpResponse::BadGateway()` instead")]
pub const HttpBadGateway: StaticResponse = StaticResponse(StatusCode::BAD_GATEWAY);
#[deprecated(since="0.5.0", note="please use `HttpResponse::ServiceUnavailable()` instead")]
pub const HttpServiceUnavailable: StaticResponse =
StaticResponse(StatusCode::SERVICE_UNAVAILABLE);
#[deprecated(since="0.5.0", note="please use `HttpResponse::GatewayTimeout()` instead")]
pub const HttpGatewayTimeout: StaticResponse =
StaticResponse(StatusCode::GATEWAY_TIMEOUT);
#[deprecated(since="0.5.0",
note="please use `HttpResponse::VersionNotSupported()` instead")]
pub const HttpVersionNotSupported: StaticResponse =
StaticResponse(StatusCode::HTTP_VERSION_NOT_SUPPORTED);
#[deprecated(since="0.5.0",
note="please use `HttpResponse::VariantAlsoNegotiates()` instead")]
pub const HttpVariantAlsoNegotiates: StaticResponse =
StaticResponse(StatusCode::VARIANT_ALSO_NEGOTIATES);
#[deprecated(since="0.5.0",
note="please use `HttpResponse::InsufficientStorage()` instead")]
pub const HttpInsufficientStorage: StaticResponse =
StaticResponse(StatusCode::INSUFFICIENT_STORAGE);
#[deprecated(since="0.5.0", note="please use `HttpResponse::LoopDetected()` instead")]
pub const HttpLoopDetected: StaticResponse = StaticResponse(StatusCode::LOOP_DETECTED);
#[deprecated(since="0.5.0", note="please use `HttpResponse` instead")]
#[derive(Copy, Clone, Debug)]
pub struct StaticResponse(StatusCode);
@ -83,12 +136,12 @@ impl StaticResponse {
req.build_response(self.0)
}
pub fn with_reason(self, reason: &'static str) -> HttpResponse {
let mut resp = HttpResponse::new(self.0, Body::Empty);
let mut resp = HttpResponse::new(self.0);
resp.set_reason(reason);
resp
}
pub fn with_body<B: Into<Body>>(self, body: B) -> HttpResponse {
HttpResponse::new(self.0, body.into())
HttpResponse::with_body(self.0, body.into())
}
}
@ -96,13 +149,13 @@ impl<S> Handler<S> for StaticResponse {
type Result = HttpResponse;
fn handle(&mut self, _: HttpRequest<S>) -> HttpResponse {
HttpResponse::new(self.0, Body::Empty)
HttpResponse::new(self.0)
}
}
impl<S> RouteHandler<S> for StaticResponse {
fn handle(&mut self, _: HttpRequest<S>) -> Reply {
Reply::response(HttpResponse::new(self.0, Body::Empty))
Reply::response(HttpResponse::new(self.0))
}
}
@ -111,19 +164,19 @@ impl Responder for StaticResponse {
type Error = Error;
fn respond_to(self, _: HttpRequest) -> Result<HttpResponse, Error> {
self.build().body(Body::Empty)
Ok(self.build().finish())
}
}
impl From<StaticResponse> for HttpResponse {
fn from(st: StaticResponse) -> Self {
HttpResponse::new(st.0, Body::Empty)
HttpResponse::new(st.0)
}
}
impl From<StaticResponse> for Reply {
fn from(st: StaticResponse) -> Self {
HttpResponse::new(st.0, Body::Empty).into()
HttpResponse::new(st.0).into()
}
}
@ -139,7 +192,14 @@ macro_rules! STATIC_RESP {
impl HttpResponse {
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!(MovedPermanenty, StatusCode::MOVED_PERMANENTLY);
@ -155,7 +215,6 @@ impl HttpResponse {
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);
@ -166,9 +225,19 @@ impl HttpResponse {
STATIC_RESP!(PreconditionFailed, StatusCode::PRECONDITION_FAILED);
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!(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)]
@ -178,7 +247,7 @@ mod tests {
#[test]
fn test_build() {
let resp = HttpOk.build().body(Body::Empty).unwrap();
let resp = HttpOk.build().body(Body::Empty);
assert_eq!(resp.status(), StatusCode::OK);
}

View File

@ -125,7 +125,7 @@ pub trait HttpMessage {
/// .from_err()
/// .and_then(|bytes: Bytes| { // <- complete body
/// println!("==== BODY ==== {:?}", bytes);
/// Ok(httpcodes::HttpOk.into())
/// Ok(HttpResponse::Ok().into())
/// }).responder()
/// }
/// # fn main() {}
@ -159,7 +159,7 @@ pub trait HttpMessage {
/// .from_err()
/// .and_then(|params| { // <- url encoded parameters
/// println!("==== BODY ==== {:?}", params);
/// Ok(httpcodes::HttpOk.into())
/// Ok(HttpResponse::Ok().into())
/// })
/// .responder()
/// }
@ -198,7 +198,7 @@ pub trait HttpMessage {
/// .from_err()
/// .and_then(|val: MyObj| { // <- deserialized value
/// println!("==== BODY ==== {:?}", val);
/// Ok(httpcodes::HttpOk.into())
/// Ok(HttpResponse::Ok().into())
/// }).responder()
/// }
/// # fn main() {}
@ -240,7 +240,7 @@ pub trait HttpMessage {
/// }
/// })
/// .finish() // <- Stream::finish() combinator from actix
/// .map(|_| httpcodes::HttpOk.into())
/// .map(|_| HttpResponse::Ok().into())
/// .responder()
/// }
/// # fn main() {}

View File

@ -205,7 +205,7 @@ impl<S> HttpRequest<S> {
if let Some(router) = self.router() {
router.server_settings().get_response(status, body)
} else {
HttpResponse::new(status, body)
HttpResponse::with_body(status, body)
}
}
@ -280,18 +280,17 @@ impl<S> HttpRequest<S> {
/// ```rust
/// # extern crate actix_web;
/// # use actix_web::{Application, HttpRequest, HttpResponse, http};
/// # use actix_web::httpcodes::HttpOk;
/// #
/// fn index(req: HttpRequest) -> HttpResponse {
/// let url = req.url_for("foo", &["1", "2", "3"]); // <- generate url for "foo" resource
/// HttpOk.into()
/// HttpResponse::Ok().into()
/// }
///
/// fn main() {
/// let app = Application::new()
/// .resource("/test/{one}/{two}/{three}", |r| {
/// r.name("foo"); // <- set resource name, then it could be used in `url_for`
/// r.method(http::Method::GET).f(|_| HttpOk);
/// r.method(http::Method::GET).f(|_| HttpResponse::Ok());
/// })
/// .finish();
/// }

View File

@ -75,8 +75,14 @@ impl HttpResponse {
/// Constructs a response
#[inline]
pub fn new(status: StatusCode, body: Body) -> HttpResponse {
HttpResponsePool::with_body(status, body)
pub fn new(status: StatusCode) -> HttpResponse {
HttpResponsePool::with_body(status, Body::Empty)
}
/// Constructs a response with body
#[inline]
pub fn with_body<B: Into<Body>>(status: StatusCode, body: B) -> HttpResponse {
HttpResponsePool::with_body(status, body.into())
}
/// Constructs a error response
@ -283,12 +289,12 @@ impl HttpResponseBuilder {
///
/// ```rust
/// # extern crate actix_web;
/// use actix_web::{HttpRequest, HttpResponse, Result, http, httpcodes};
/// use actix_web::{HttpRequest, HttpResponse, Result, http};
///
/// fn index(req: HttpRequest) -> Result<HttpResponse> {
/// Ok(httpcodes::HttpOk.build()
/// Ok(HttpResponse::Ok()
/// .set(http::header::IfModifiedSince("Sun, 07 Nov 1994 08:48:37 GMT".parse()?))
/// .finish()?)
/// .finish())
/// }
/// fn main() {}
/// ```
@ -307,18 +313,14 @@ impl HttpResponseBuilder {
/// Set a header.
///
/// ```rust
/// # extern crate http;
/// # extern crate actix_web;
/// # use actix_web::*;
/// # use actix_web::httpcodes::*;
/// #
/// use http::header;
/// use actix_web::{http, Application, HttpRequest, HttpResponse};
///
/// fn index(req: HttpRequest) -> Result<HttpResponse> {
/// Ok(HttpOk.build()
/// fn index(req: HttpRequest) -> HttpResponse {
/// HttpResponse::Ok()
/// .header("X-TEST", "value")
/// .header(header::CONTENT_TYPE, "application/json")
/// .finish()?)
/// .header(http::header::CONTENT_TYPE, "application/json")
/// .finish()
/// }
/// fn main() {}
/// ```
@ -429,10 +431,10 @@ impl HttpResponseBuilder {
///
/// ```rust
/// # extern crate actix_web;
/// use actix_web::{HttpRequest, HttpResponse, Result, http, httpcodes};
/// use actix_web::{http, HttpRequest, HttpResponse, Result};
///
/// fn index(req: HttpRequest) -> Result<HttpResponse> {
/// Ok(httpcodes::HttpOk.build()
/// fn index(req: HttpRequest) -> HttpResponse {
/// HttpResponse::Ok()
/// .cookie(
/// http::Cookie::build("name", "value")
/// .domain("www.rust-lang.org")
@ -440,7 +442,7 @@ impl HttpResponseBuilder {
/// .secure(true)
/// .http_only(true)
/// .finish())
/// .finish()?)
/// .finish()
/// }
/// fn main() {}
/// ```
@ -506,26 +508,28 @@ impl HttpResponseBuilder {
/// Set a body and generate `HttpResponse`.
///
/// `HttpResponseBuilder` can not be used after this call.
pub fn body<B: Into<Body>>(&mut self, body: B) -> Result<HttpResponse, Error> {
pub fn body<B: Into<Body>>(&mut self, body: B) -> HttpResponse {
if let Some(e) = self.err.take() {
return Err(e.into())
return Error::from(e).into()
}
let mut response = self.response.take().expect("cannot reuse response builder");
if let Some(ref jar) = self.cookies {
for cookie in jar.delta() {
response.headers.append(
header::SET_COOKIE,
HeaderValue::from_str(&cookie.to_string())?);
match HeaderValue::from_str(&cookie.to_string()) {
Ok(val) => response.headers.append(header::SET_COOKIE, val),
Err(e) => return Error::from(e).into(),
};
}
}
response.body = body.into();
Ok(HttpResponse(Some(response), self.pool.take().unwrap()))
HttpResponse(Some(response), self.pool.take().unwrap())
}
#[inline]
/// Set a streaming body and generate `HttpResponse`.
///
/// `HttpResponseBuilder` can not be used after this call.
pub fn streaming<S, E>(&mut self, stream: S) -> Result<HttpResponse, Error>
pub fn streaming<S, E>(&mut self, stream: S) -> HttpResponse
where S: Stream<Item=Bytes, Error=E> + 'static,
E: Into<Error>,
{
@ -535,10 +539,11 @@ impl HttpResponseBuilder {
/// Set a json body and generate `HttpResponse`
///
/// `HttpResponseBuilder` can not be used after this call.
pub fn json<T: Serialize>(&mut self, value: T) -> Result<HttpResponse, Error> {
let body = serde_json::to_string(&value)?;
let contains = if let Some(parts) = parts(&mut self.response, &self.err) {
pub fn json<T: Serialize>(&mut self, value: T) -> HttpResponse {
match serde_json::to_string(&value) {
Ok(body) => {
let contains =
if let Some(parts) = parts(&mut self.response, &self.err) {
parts.headers.contains_key(header::CONTENT_TYPE)
} else {
true
@ -547,13 +552,17 @@ impl HttpResponseBuilder {
self.header(header::CONTENT_TYPE, "application/json");
}
Ok(self.body(body)?)
self.body(body)
},
Err(e) => Error::from(e).into()
}
}
#[inline]
/// Set an empty body and generate `HttpResponse`
///
/// `HttpResponseBuilder` can not be used after this call.
pub fn finish(&mut self) -> Result<HttpResponse, Error> {
pub fn finish(&mut self) -> HttpResponse {
self.body(Body::Empty)
}
@ -591,7 +600,7 @@ impl<I: Into<HttpResponse>, E: Into<Error>> From<Result<I, E>> for HttpResponse
impl From<HttpResponseBuilder> for HttpResponse {
fn from(mut builder: HttpResponseBuilder) -> Self {
builder.finish().into()
builder.finish()
}
}
@ -601,16 +610,15 @@ impl Responder for HttpResponseBuilder {
#[inline]
fn respond_to(mut self, _: HttpRequest) -> Result<HttpResponse, Error> {
self.finish()
Ok(self.finish())
}
}
impl From<&'static str> for HttpResponse {
fn from(val: &'static str) -> Self {
HttpResponse::build(StatusCode::OK)
HttpResponse::Ok()
.content_type("text/plain; charset=utf-8")
.body(val)
.into()
}
}
@ -619,18 +627,17 @@ impl Responder for &'static str {
type Error = Error;
fn respond_to(self, _: HttpRequest) -> Result<HttpResponse, Error> {
HttpResponse::build(StatusCode::OK)
Ok(HttpResponse::Ok()
.content_type("text/plain; charset=utf-8")
.body(self)
.body(self))
}
}
impl From<&'static [u8]> for HttpResponse {
fn from(val: &'static [u8]) -> Self {
HttpResponse::build(StatusCode::OK)
HttpResponse::Ok()
.content_type("application/octet-stream")
.body(val)
.into()
}
}
@ -639,18 +646,17 @@ impl Responder for &'static [u8] {
type Error = Error;
fn respond_to(self, _: HttpRequest) -> Result<HttpResponse, Error> {
HttpResponse::build(StatusCode::OK)
Ok(HttpResponse::Ok()
.content_type("application/octet-stream")
.body(self)
.body(self))
}
}
impl From<String> for HttpResponse {
fn from(val: String) -> Self {
HttpResponse::build(StatusCode::OK)
HttpResponse::Ok()
.content_type("text/plain; charset=utf-8")
.body(val)
.into()
}
}
@ -659,9 +665,9 @@ impl Responder for String {
type Error = Error;
fn respond_to(self, _: HttpRequest) -> Result<HttpResponse, Error> {
HttpResponse::build(StatusCode::OK)
Ok(HttpResponse::Ok()
.content_type("text/plain; charset=utf-8")
.body(self)
.body(self))
}
}
@ -670,7 +676,6 @@ impl<'a> From<&'a String> for HttpResponse {
HttpResponse::build(StatusCode::OK)
.content_type("text/plain; charset=utf-8")
.body(val)
.into()
}
}
@ -679,18 +684,17 @@ impl<'a> Responder for &'a String {
type Error = Error;
fn respond_to(self, _: HttpRequest) -> Result<HttpResponse, Error> {
HttpResponse::build(StatusCode::OK)
Ok(HttpResponse::Ok()
.content_type("text/plain; charset=utf-8")
.body(self)
.body(self))
}
}
impl From<Bytes> for HttpResponse {
fn from(val: Bytes) -> Self {
HttpResponse::build(StatusCode::OK)
HttpResponse::Ok()
.content_type("application/octet-stream")
.body(val)
.into()
}
}
@ -699,18 +703,17 @@ impl Responder for Bytes {
type Error = Error;
fn respond_to(self, _: HttpRequest) -> Result<HttpResponse, Error> {
HttpResponse::build(StatusCode::OK)
Ok(HttpResponse::Ok()
.content_type("application/octet-stream")
.body(self)
.body(self))
}
}
impl From<BytesMut> for HttpResponse {
fn from(val: BytesMut) -> Self {
HttpResponse::build(StatusCode::OK)
HttpResponse::Ok()
.content_type("application/octet-stream")
.body(val)
.into()
}
}
@ -719,9 +722,9 @@ impl Responder for BytesMut {
type Error = Error;
fn respond_to(self, _: HttpRequest) -> Result<HttpResponse, Error> {
HttpResponse::build(StatusCode::OK)
Ok(HttpResponse::Ok()
.content_type("application/octet-stream")
.body(self)
.body(self))
}
}
@ -744,7 +747,7 @@ impl<'a, S> From<&'a HttpRequest<S>> for HttpResponseBuilder {
if let Some(router) = req.router() {
router.server_settings().get_response_builder(StatusCode::OK)
} else {
HttpResponse::build(StatusCode::OK)
HttpResponse::Ok()
}
}
}
@ -870,14 +873,14 @@ mod tests {
use http::{Method, Uri};
use http::header::{COOKIE, CONTENT_TYPE, HeaderValue};
use body::Binary;
use {http, httpcodes};
use http;
#[test]
fn test_debug() {
let resp = HttpResponse::Ok()
.header(COOKIE, HeaderValue::from_static("cookie1=value1; "))
.header(COOKIE, HeaderValue::from_static("cookie2=value2; "))
.finish().unwrap();
.finish();
let dbg = format!("{:?}", resp);
assert!(dbg.contains("HttpResponse"));
}
@ -892,8 +895,7 @@ mod tests {
Method::GET, Uri::from_str("/").unwrap(), Version::HTTP_11, headers, None);
let cookies = req.cookies().unwrap();
let resp = httpcodes::HttpOk
.build()
let resp = HttpResponse::Ok()
.cookie(http::Cookie::build("name", "value")
.domain("www.rust-lang.org")
.path("/test")
@ -901,10 +903,7 @@ mod tests {
.max_age(Duration::days(1))
.finish())
.del_cookie(&cookies[0])
.body(Body::Empty);
assert!(resp.is_ok());
let resp = resp.unwrap();
.finish();
let mut val: Vec<_> = resp.headers().get_all("Set-Cookie")
.iter().map(|v| v.to_str().unwrap().to_owned()).collect();
@ -919,53 +918,51 @@ mod tests {
let resp = HttpResponse::Ok()
.header("X-TEST", "value")
.version(Version::HTTP_10)
.finish().unwrap();
.finish();
assert_eq!(resp.version(), Some(Version::HTTP_10));
assert_eq!(resp.status(), StatusCode::OK);
}
#[test]
fn test_upgrade() {
let resp = HttpResponse::build(StatusCode::OK)
.upgrade().body(Body::Empty).unwrap();
let resp = HttpResponse::build(StatusCode::OK).upgrade().finish();
assert!(resp.upgrade())
}
#[test]
fn test_force_close() {
let resp = HttpResponse::build(StatusCode::OK)
.force_close().body(Body::Empty).unwrap();
let resp = HttpResponse::build(StatusCode::OK).force_close().finish();
assert!(!resp.keep_alive().unwrap())
}
#[test]
fn test_content_type() {
let resp = HttpResponse::build(StatusCode::OK)
.content_type("text/plain").body(Body::Empty).unwrap();
.content_type("text/plain").body(Body::Empty);
assert_eq!(resp.headers().get(CONTENT_TYPE).unwrap(), "text/plain")
}
#[test]
fn test_content_encoding() {
let resp = HttpResponse::build(StatusCode::OK).finish().unwrap();
let resp = HttpResponse::build(StatusCode::OK).finish();
assert_eq!(resp.content_encoding(), None);
#[cfg(feature="brotli")]
{
let resp = HttpResponse::build(StatusCode::OK)
.content_encoding(ContentEncoding::Br).finish().unwrap();
.content_encoding(ContentEncoding::Br).finish();
assert_eq!(resp.content_encoding(), Some(ContentEncoding::Br));
}
let resp = HttpResponse::build(StatusCode::OK)
.content_encoding(ContentEncoding::Gzip).finish().unwrap();
.content_encoding(ContentEncoding::Gzip).finish();
assert_eq!(resp.content_encoding(), Some(ContentEncoding::Gzip));
}
#[test]
fn test_json() {
let resp = HttpResponse::build(StatusCode::OK)
.json(vec!["v1", "v2", "v3"]).unwrap();
.json(vec!["v1", "v2", "v3"]);
let ct = resp.headers().get(CONTENT_TYPE).unwrap();
assert_eq!(ct, HeaderValue::from_static("application/json"));
assert_eq!(*resp.body(), Body::from(Bytes::from_static(b"[\"v1\",\"v2\",\"v3\"]")));
@ -975,7 +972,7 @@ mod tests {
fn test_json_ct() {
let resp = HttpResponse::build(StatusCode::OK)
.header(CONTENT_TYPE, "text/json")
.json(vec!["v1", "v2", "v3"]).unwrap();
.json(vec!["v1", "v2", "v3"]);
let ct = resp.headers().get(CONTENT_TYPE).unwrap();
assert_eq!(ct, HeaderValue::from_static("text/json"));
assert_eq!(*resp.body(), Body::from(Bytes::from_static(b"[\"v1\",\"v2\",\"v3\"]")));
@ -1089,7 +1086,7 @@ mod tests {
assert_eq!(resp.status(), StatusCode::OK);
let mut builder = resp.into_builder();
let resp = builder.status(StatusCode::BAD_REQUEST).finish().unwrap();
let resp = builder.status(StatusCode::BAD_REQUEST).finish();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
}

View File

@ -106,7 +106,7 @@ impl<T: Serialize> Responder for Json<T> {
Ok(HttpResponse::Ok()
.content_type("application/json")
.body(body)?)
.body(body))
}
}
@ -140,7 +140,7 @@ impl<T, S> FromRequest<S> for Json<T>
/// # #[macro_use] extern crate serde_derive;
/// use futures::future::Future;
/// use actix_web::{Application, AsyncResponder,
/// HttpRequest, HttpResponse, HttpMessage, Error, httpcodes};
/// HttpRequest, HttpResponse, HttpMessage, Error};
///
/// #[derive(Deserialize, Debug)]
/// struct MyObj {
@ -152,7 +152,7 @@ impl<T, S> FromRequest<S> for Json<T>
/// .from_err()
/// .and_then(|val: MyObj| { // <- deserialized value
/// println!("==== BODY ==== {:?}", val);
/// Ok(httpcodes::HttpOk.into())
/// Ok(HttpResponse::Ok().into())
/// }).responder()
/// }
/// # fn main() {}

View File

@ -127,7 +127,6 @@ pub mod client;
pub mod fs;
pub mod ws;
pub mod error;
pub mod httpcodes;
pub mod multipart;
pub mod middleware;
pub mod pred;
@ -145,6 +144,9 @@ pub use handler::{Either, Responder, AsyncResponder, FutureResponse, State};
pub use context::HttpContext;
pub use server::HttpServer;
#[doc(hidden)]
pub mod httpcodes;
#[cfg(feature="openssl")]
pub(crate) const HAS_OPENSSL: bool = true;
#[cfg(not(feature="openssl"))]

View File

@ -18,7 +18,7 @@
//!
//! ```rust
//! # extern crate actix_web;
//! use actix_web::{Application, HttpRequest, http, httpcodes};
//! use actix_web::{http, Application, HttpRequest, HttpResponse};
//! use actix_web::middleware::cors;
//!
//! fn index(mut req: HttpRequest) -> &'static str {
@ -36,8 +36,8 @@
//! .max_age(3600)
//! .finish().expect("Can not create CORS middleware")
//! .register(r); // <- Register CORS middleware
//! r.method(http::Method::GET).f(|_| httpcodes::HttpOk);
//! r.method(http::Method::HEAD).f(|_| httpcodes::HttpMethodNotAllowed);
//! r.method(http::Method::GET).f(|_| HttpResponse::Ok());
//! r.method(http::Method::HEAD).f(|_| HttpResponse::MethodNotAllowed());
//! })
//! .finish();
//! }
@ -48,7 +48,7 @@
use std::collections::HashSet;
use std::iter::FromIterator;
use http::{self, Method, HttpTryFrom, Uri};
use http::{self, Method, HttpTryFrom, Uri, StatusCode};
use http::header::{self, HeaderName, HeaderValue};
use error::{Result, ResponseError};
@ -56,7 +56,6 @@ use resource::Resource;
use httpmessage::HttpMessage;
use httprequest::HttpRequest;
use httpresponse::HttpResponse;
use httpcodes::{HttpOk, HttpBadRequest};
use middleware::{Middleware, Response, Started};
/// A set of errors that can occur during processing CORS
@ -108,7 +107,7 @@ pub enum CorsBuilderError {
impl ResponseError for CorsError {
fn error_response(&self) -> HttpResponse {
HttpBadRequest.build().body(format!("{}", self)).unwrap()
HttpResponse::with_body(StatusCode::BAD_REQUEST, format!("{}", self))
}
}
@ -217,7 +216,7 @@ impl Cors {
/// method, but in that case *Cors* middleware wont be able to handle *OPTIONS*
/// requests.
pub fn register<S: 'static>(self, resource: &mut Resource<S>) {
resource.method(Method::OPTIONS).h(HttpOk);
resource.method(Method::OPTIONS).h(|_| HttpResponse::Ok());
resource.middleware(self);
}
@ -305,7 +304,7 @@ impl<S> Middleware<S> for Cors {
};
Ok(Started::Response(
HttpOk.build()
HttpResponse::Ok()
.if_some(self.max_age.as_ref(), |max_age, resp| {
let _ = resp.header(
header::ACCESS_CONTROL_MAX_AGE, format!("{}", max_age).as_str());})
@ -332,8 +331,7 @@ impl<S> Middleware<S> for Cors {
header::ACCESS_CONTROL_ALLOW_METHODS,
&self.methods.iter().fold(
String::new(), |s, v| s + "," + v.as_str()).as_str()[1..])
.finish()
.unwrap()))
.finish()))
} else {
self.validate_origin(req)?;
@ -809,7 +807,7 @@ mod tests {
let cors = Cors::build().finish().unwrap();
let mut req = TestRequest::default().method(Method::GET).finish();
let resp: HttpResponse = HttpOk.into();
let resp: HttpResponse = HttpResponse::Ok().into();
let resp = cors.response(&mut req, resp).unwrap().response();
assert!(resp.headers().get(header::ACCESS_CONTROL_ALLOW_ORIGIN).is_none());
@ -839,7 +837,7 @@ mod tests {
.method(Method::OPTIONS)
.finish();
let resp: HttpResponse = HttpOk.into();
let resp: HttpResponse = HttpResponse::Ok().into();
let resp = cors.response(&mut req, resp).unwrap().response();
assert_eq!(
&b"*"[..],
@ -848,9 +846,9 @@ mod tests {
&b"Origin"[..],
resp.headers().get(header::VARY).unwrap().as_bytes());
let resp: HttpResponse = HttpOk.build()
let resp: HttpResponse = HttpResponse::Ok()
.header(header::VARY, "Accept")
.finish().unwrap();
.finish();
let resp = cors.response(&mut req, resp).unwrap().response();
assert_eq!(
&b"Accept, Origin"[..],
@ -860,7 +858,7 @@ mod tests {
.disable_vary_header()
.allowed_origin("https://www.example.com")
.finish().unwrap();
let resp: HttpResponse = HttpOk.into();
let resp: HttpResponse = HttpResponse::Ok().into();
let resp = cors.response(&mut req, resp).unwrap().response();
assert_eq!(
&b"https://www.example.com"[..],

View File

@ -22,7 +22,7 @@
//!
//! ```
//! # extern crate actix_web;
//! use actix_web::{Application, HttpRequest, http, httpcodes};
//! use actix_web::{http, Application, HttpRequest, HttpResponse};
//! use actix_web::middleware::csrf;
//!
//! fn handle_post(_: HttpRequest) -> &'static str {
@ -36,7 +36,7 @@
//! .allowed_origin("https://www.example.com")
//! .finish())
//! .resource("/", |r| {
//! r.method(http::Method::GET).f(|_| httpcodes::HttpOk);
//! r.method(http::Method::GET).f(|_| HttpResponse::Ok());
//! r.method(http::Method::POST).f(handle_post);
//! })
//! .finish();
@ -51,10 +51,9 @@ use std::collections::HashSet;
use bytes::Bytes;
use error::{Result, ResponseError};
use http::{HeaderMap, HttpTryFrom, Uri, header};
use httpmessage::HttpMessage;
use httprequest::HttpRequest;
use httpresponse::HttpResponse;
use httpmessage::HttpMessage;
use httpcodes::HttpForbidden;
use middleware::{Middleware, Started};
/// Potential cross-site request forgery detected.
@ -73,7 +72,7 @@ pub enum CsrfError {
impl ResponseError for CsrfError {
fn error_response(&self) -> HttpResponse {
HttpForbidden.build().body(self.to_string()).unwrap()
HttpResponse::Forbidden().body(self.to_string())
}
}

View File

@ -13,7 +13,7 @@ use middleware::{Response, Middleware};
///
/// ```rust
/// # extern crate actix_web;
/// use actix_web::{Application, http, httpcodes, middleware};
/// use actix_web::{http, middleware, Application, HttpResponse};
///
/// fn main() {
/// let app = Application::new()
@ -22,8 +22,8 @@ use middleware::{Response, Middleware};
/// .header("X-Version", "0.2")
/// .finish())
/// .resource("/test", |r| {
/// r.method(http::Method::GET).f(|_| httpcodes::HttpOk);
/// r.method(http::Method::HEAD).f(|_| httpcodes::HttpMethodNotAllowed);
/// r.method(http::Method::GET).f(|_| HttpResponse::Ok());
/// r.method(http::Method::HEAD).f(|_| HttpResponse::MethodNotAllowed());
/// })
/// .finish();
/// }
@ -112,14 +112,14 @@ mod tests {
let mut req = HttpRequest::default();
let resp = HttpResponse::Ok().finish().unwrap();
let resp = HttpResponse::Ok().finish();
let resp = match mw.response(&mut req, resp) {
Ok(Response::Done(resp)) => resp,
_ => panic!(),
};
assert_eq!(resp.headers().get(CONTENT_TYPE).unwrap(), "0001");
let resp = HttpResponse::Ok().header(CONTENT_TYPE, "0002").finish().unwrap();
let resp = HttpResponse::Ok().header(CONTENT_TYPE, "0002").finish();
let resp = match mw.response(&mut req, resp) {
Ok(Response::Done(resp)) => resp,
_ => panic!(),

View File

@ -294,7 +294,6 @@ impl<'a> fmt::Display for FormatDisplay<'a> {
#[cfg(test)]
mod tests {
use Body;
use super::*;
use std::str::FromStr;
use time;
@ -311,7 +310,8 @@ mod tests {
Method::GET, Uri::from_str("/").unwrap(), Version::HTTP_11, headers, None);
let resp = HttpResponse::build(StatusCode::OK)
.header("X-Test", "ttt")
.force_close().body(Body::Empty).unwrap();
.force_close()
.finish();
match logger.start(&mut req) {
Ok(Started::Done) => (),
@ -340,8 +340,7 @@ mod tests {
headers.insert(header::USER_AGENT, header::HeaderValue::from_static("ACTIX-WEB"));
let req = HttpRequest::new(
Method::GET, Uri::from_str("/").unwrap(), Version::HTTP_11, headers, None);
let resp = HttpResponse::build(StatusCode::OK)
.force_close().body(Body::Empty).unwrap();
let resp = HttpResponse::build(StatusCode::OK).force_close().finish();
let entry_time = time::now();
let render = |fmt: &mut Formatter| {
@ -358,8 +357,7 @@ mod tests {
let req = HttpRequest::new(
Method::GET, Uri::from_str("/?test").unwrap(),
Version::HTTP_11, HeaderMap::new(), None);
let resp = HttpResponse::build(StatusCode::OK)
.force_close().body(Body::Empty).unwrap();
let resp = HttpResponse::build(StatusCode::OK).force_close().finish();
let entry_time = time::now();
let render = |fmt: &mut Formatter| {

View File

@ -20,16 +20,13 @@ pub trait Predicate<S> {
///
/// ```rust
/// # extern crate actix_web;
/// # extern crate http;
/// # use actix_web::*;
/// # use actix_web::httpcodes::*;
/// use actix_web::pred;
/// use actix_web::{pred, Application, HttpResponse};
///
/// fn main() {
/// Application::new()
/// .resource("/index.html", |r| r.route()
/// .filter(pred::Any(pred::Get()).or(pred::Post()))
/// .h(HttpMethodNotAllowed));
/// .f(|r| HttpResponse::MethodNotAllowed()));
/// }
/// ```
pub fn Any<S: 'static, P: Predicate<S> + 'static>(pred: P) -> AnyPredicate<S>
@ -63,17 +60,14 @@ impl<S: 'static> Predicate<S> for AnyPredicate<S> {
///
/// ```rust
/// # extern crate actix_web;
/// # extern crate http;
/// # use actix_web::*;
/// # use actix_web::httpcodes::*;
/// use actix_web::pred;
/// use actix_web::{pred, Application, HttpResponse};
///
/// fn main() {
/// Application::new()
/// .resource("/index.html", |r| r.route()
/// .filter(pred::All(pred::Get())
/// .and(pred::Header("content-type", "plain/text")))
/// .h(HttpMethodNotAllowed));
/// .f(|_| HttpResponse::MethodNotAllowed()));
/// }
/// ```
pub fn All<S: 'static, P: Predicate<S> + 'static>(pred: P) -> AllPredicate<S> {

View File

@ -5,7 +5,6 @@ use smallvec::SmallVec;
use http::{Method, StatusCode};
use pred;
use body::Body;
use route::Route;
use handler::{Reply, Handler, Responder, FromRequest};
use middleware::Middleware;
@ -172,7 +171,7 @@ impl<S: 'static> Resource<S> {
if let Some(resource) = default {
resource.handle(req, None)
} else {
Reply::response(HttpResponse::new(StatusCode::NOT_FOUND, Body::Empty))
Reply::response(HttpResponse::new(StatusCode::NOT_FOUND))
}
}
}

View File

@ -5,10 +5,10 @@ use futures::{Async, Future, Poll};
use error::Error;
use pred::Predicate;
use http::StatusCode;
use handler::{Reply, ReplyItem, Handler, FromRequest,
Responder, RouteHandler, AsyncHandler, WrapHandler};
use middleware::{Middleware, Response as MiddlewareResponse, Started as MiddlewareStarted};
use httpcodes::HttpNotFound;
use httprequest::HttpRequest;
use httpresponse::HttpResponse;
use with::{with, with2, with3, WithHandler};
@ -27,7 +27,7 @@ impl<S: 'static> Default for Route<S> {
fn default() -> Route<S> {
Route {
preds: Vec::new(),
handler: InnerHandler::new(|_| HttpNotFound),
handler: InnerHandler::new(|_| HttpResponse::new(StatusCode::NOT_FOUND)),
}
}
}
@ -61,14 +61,13 @@ impl<S: 'static> Route<S> {
/// ```rust
/// # extern crate actix_web;
/// # use actix_web::*;
/// # use actix_web::httpcodes::*;
/// # fn main() {
/// Application::new()
/// .resource("/path", |r|
/// r.route()
/// .filter(pred::Get())
/// .filter(pred::Header("content-type", "text/plain"))
/// .f(|req| HttpOk)
/// .f(|req| HttpResponse::Ok())
/// )
/// # .finish();
/// # }

View File

@ -15,8 +15,8 @@ use futures::{Future, Poll, Async};
use tokio_core::reactor::Timeout;
use pipeline::Pipeline;
use httpcodes::HttpNotFound;
use httprequest::HttpRequest;
use httpresponse::HttpResponse;
use error::{ParseError, PayloadError, ResponseError};
use payload::{Payload, PayloadWriter, PayloadStatus};
@ -158,7 +158,7 @@ impl<T, H> Http1<T, H>
}
self.tasks.push_back(
Entry {pipe: Pipeline::error(HttpNotFound),
Entry {pipe: Pipeline::error(HttpResponse::NotFound()),
flags: EntryFlags::empty()});
continue
},

View File

@ -18,9 +18,9 @@ use tokio_core::reactor::Timeout;
use pipeline::Pipeline;
use error::PayloadError;
use httpcodes::HttpNotFound;
use httpmessage::HttpMessage;
use httprequest::HttpRequest;
use httpresponse::HttpResponse;
use payload::{Payload, PayloadWriter, PayloadStatus};
use super::h2writer::H2Writer;
@ -318,7 +318,7 @@ impl<H: 'static> Entry<H> {
}
}
Entry {task: task.unwrap_or_else(|| Pipeline::error(HttpNotFound)),
Entry {task: task.unwrap_or_else(|| Pipeline::error(HttpResponse::NotFound())),
payload: psender,
stream: H2Writer::new(
resp, settings.get_shared_bytes(), Rc::clone(settings)),

View File

@ -33,6 +33,26 @@ use httpresponse::HttpResponse;
pub(crate) const MAX_WRITE_BUFFER_SIZE: usize = 65_536;
/// Create new http server with application factory
///
/// ```rust
/// # extern crate actix;
/// # extern crate actix_web;
/// use actix::*;
/// use actix_web::{server, Application, HttpResponse};
///
/// fn main() {
/// let sys = actix::System::new("guide");
///
/// server::new(
/// || Application::new()
/// .resource("/", |r| r.f(|_| HttpResponse::Ok())))
/// .bind("127.0.0.1:59080").unwrap()
/// .start();
///
/// # actix::Arbiter::system().do_send(actix::msgs::SystemExit(0));
/// let _ = sys.run();
/// }
/// ```
pub fn new<F, U, H>(factory: F) -> HttpServer<H>
where F: Fn() -> U + Sync + Send + 'static,
U: IntoIterator<Item=H> + 'static,

View File

@ -269,7 +269,7 @@ impl<H: IntoHttpHandler> HttpServer<H>
///
/// HttpServer::new(
/// || Application::new()
/// .resource("/", |r| r.h(httpcodes::HttpOk)))
/// .resource("/", |r| r.h(|_| HttpResponse::Ok())))
/// .bind("127.0.0.1:0").expect("Can not bind to 127.0.0.1:0")
/// .start();
/// # actix::Arbiter::system().do_send(actix::msgs::SystemExit(0));
@ -327,7 +327,7 @@ impl<H: IntoHttpHandler> HttpServer<H>
/// fn main() {
/// HttpServer::new(
/// || Application::new()
/// .resource("/", |r| r.h(httpcodes::HttpOk)))
/// .resource("/", |r| r.h(|_| HttpResponse::Ok())))
/// .bind("127.0.0.1:0").expect("Can not bind to 127.0.0.1:0")
/// .run();
/// }

View File

@ -46,7 +46,7 @@ use client::{ClientRequest, ClientRequestBuilder, ClientConnector};
/// # use actix_web::*;
/// #
/// # fn my_handler(req: HttpRequest) -> HttpResponse {
/// # httpcodes::HttpOk.into()
/// # HttpResponse::Ok().into()
/// # }
/// #
/// # fn main() {
@ -341,16 +341,6 @@ impl<S: 'static> TestApp<S> {
self.app = Some(self.app.take().unwrap().resource("/", |r| r.h(handler)));
}
/// Register handler for "/" with resource middleware
pub fn handler2<H, M>(&mut self, handler: H, mw: M)
where H: Handler<S>, M: Middleware<S>
{
self.app = Some(self.app.take().unwrap()
.resource("/", |r| {
r.middleware(mw);
r.h(handler)}));
}
/// Register middleware
pub fn middleware<T>(&mut self, mw: T) -> &mut TestApp<S>
where T: Middleware<S> + 'static
@ -401,9 +391,9 @@ impl<S: 'static> Iterator for TestApp<S> {
///
/// fn index(req: HttpRequest) -> HttpResponse {
/// if let Some(hdr) = req.headers().get(header::CONTENT_TYPE) {
/// httpcodes::HttpOk.into()
/// HttpResponse::Ok().into()
/// } else {
/// httpcodes::HttpBadRequest.into()
/// HttpResponse::BadRequest().into()
/// }
/// }
///

View File

@ -55,7 +55,6 @@ use error::{Error, PayloadError, ResponseError};
use httpmessage::HttpMessage;
use httprequest::HttpRequest;
use httpresponse::{ConnectionType, HttpResponse, HttpResponseBuilder};
use httpcodes::{HttpBadRequest, HttpMethodNotAllowed};
mod frame;
mod proto;
@ -138,22 +137,18 @@ impl ResponseError for HandshakeError {
fn error_response(&self) -> HttpResponse {
match *self {
HandshakeError::GetMethodRequired => {
HttpMethodNotAllowed
.build()
.header(header::ALLOW, "GET")
.finish()
.unwrap()
HttpResponse::MethodNotAllowed().header(header::ALLOW, "GET").finish()
}
HandshakeError::NoWebsocketUpgrade =>
HttpBadRequest.with_reason("No WebSocket UPGRADE header found"),
HandshakeError::NoConnectionUpgrade =>
HttpBadRequest.with_reason("No CONNECTION upgrade"),
HandshakeError::NoVersionHeader =>
HttpBadRequest.with_reason("Websocket version header is required"),
HandshakeError::UnsupportedVersion =>
HttpBadRequest.with_reason("Unsupported version"),
HandshakeError::BadWebsocketKey =>
HttpBadRequest.with_reason("Handshake error"),
HandshakeError::NoWebsocketUpgrade => HttpResponse::BadRequest()
.reason("No WebSocket UPGRADE header found").finish(),
HandshakeError::NoConnectionUpgrade => HttpResponse::BadRequest()
.reason("No CONNECTION upgrade").finish(),
HandshakeError::NoVersionHeader => HttpResponse::BadRequest()
.reason("Websocket version header is required").finish(),
HandshakeError::UnsupportedVersion => HttpResponse::BadRequest()
.reason("Unsupported version").finish(),
HandshakeError::BadWebsocketKey => HttpResponse::BadRequest()
.reason("Handshake error").finish(),
}
}
}
@ -179,7 +174,7 @@ pub fn start<A, S>(req: HttpRequest<S>, actor: A) -> Result<HttpResponse, Error>
let mut ctx = WebsocketContext::new(req, actor);
ctx.add_stream(stream);
Ok(resp.body(ctx)?)
Ok(resp.body(ctx))
}
/// Prepare `WebSocket` handshake response.
@ -408,7 +403,7 @@ mod tests {
let req = HttpRequest::new(Method::GET, Uri::from_str("/").unwrap(),
Version::HTTP_11, headers, None);
assert_eq!(StatusCode::SWITCHING_PROTOCOLS,
handshake(&req).unwrap().finish().unwrap().status());
handshake(&req).unwrap().finish().status());
}
#[test]

View File

@ -43,7 +43,7 @@ const STR: &str =
#[test]
fn test_simple() {
let mut srv = test::TestServer::new(
|app| app.handler(|_| httpcodes::HttpOk.build().body(STR)));
|app| app.handler(|_| HttpResponse::Ok().body(STR)));
let request = srv.get().header("x-test", "111").finish().unwrap();
let repr = format!("{:?}", request);
@ -70,8 +70,8 @@ fn test_simple() {
fn test_with_query_parameter() {
let mut srv = test::TestServer::new(
|app| app.handler(|req: HttpRequest| match req.query().get("qp") {
Some(_) => httpcodes::HttpOk.build().finish(),
None => httpcodes::HttpBadRequest.build().finish(),
Some(_) => HttpResponse::Ok().finish(),
None => HttpResponse::BadRequest().finish(),
}));
let request = srv.get().uri(srv.url("/?qp=5").as_str()).finish().unwrap();
@ -84,7 +84,7 @@ fn test_with_query_parameter() {
#[test]
fn test_no_decompress() {
let mut srv = test::TestServer::new(
|app| app.handler(|_| httpcodes::HttpOk.build().body(STR)));
|app| app.handler(|_| HttpResponse::Ok().body(STR)));
let request = srv.get().disable_decompress().finish().unwrap();
let response = srv.execute(request.send()).unwrap();
@ -114,8 +114,7 @@ fn test_client_gzip_encoding() {
let mut srv = test::TestServer::new(|app| app.handler(|req: HttpRequest| {
req.body()
.and_then(|bytes: Bytes| {
Ok(httpcodes::HttpOk
.build()
Ok(HttpResponse::Ok()
.content_encoding(http::ContentEncoding::Deflate)
.body(bytes))
}).responder()}
@ -140,8 +139,7 @@ fn test_client_gzip_encoding_large() {
let mut srv = test::TestServer::new(|app| app.handler(|req: HttpRequest| {
req.body()
.and_then(|bytes: Bytes| {
Ok(httpcodes::HttpOk
.build()
Ok(HttpResponse::Ok()
.content_encoding(http::ContentEncoding::Deflate)
.body(bytes))
}).responder()}
@ -169,8 +167,7 @@ fn test_client_gzip_encoding_large_random() {
let mut srv = test::TestServer::new(|app| app.handler(|req: HttpRequest| {
req.body()
.and_then(|bytes: Bytes| {
Ok(httpcodes::HttpOk
.build()
Ok(HttpResponse::Ok()
.content_encoding(http::ContentEncoding::Deflate)
.body(bytes))
}).responder()}
@ -194,8 +191,7 @@ fn test_client_brotli_encoding() {
let mut srv = test::TestServer::new(|app| app.handler(|req: HttpRequest| {
req.body()
.and_then(|bytes: Bytes| {
Ok(httpcodes::HttpOk
.build()
Ok(HttpResponse::Ok()
.content_encoding(http::ContentEncoding::Gzip)
.body(bytes))
}).responder()}
@ -224,8 +220,7 @@ fn test_client_brotli_encoding_large_random() {
let mut srv = test::TestServer::new(|app| app.handler(|req: HttpRequest| {
req.body()
.and_then(move |bytes: Bytes| {
Ok(httpcodes::HttpOk
.build()
Ok(HttpResponse::Ok()
.content_encoding(http::ContentEncoding::Gzip)
.body(bytes))
}).responder()}
@ -250,8 +245,7 @@ fn test_client_deflate_encoding() {
let mut srv = test::TestServer::new(|app| app.handler(|req: HttpRequest| {
req.body()
.and_then(|bytes: Bytes| {
Ok(httpcodes::HttpOk
.build()
Ok(HttpResponse::Ok()
.content_encoding(http::ContentEncoding::Br)
.body(bytes))
}).responder()}
@ -280,8 +274,7 @@ fn test_client_deflate_encoding_large_random() {
let mut srv = test::TestServer::new(|app| app.handler(|req: HttpRequest| {
req.body()
.and_then(|bytes: Bytes| {
Ok(httpcodes::HttpOk
.build()
Ok(HttpResponse::Ok()
.content_encoding(http::ContentEncoding::Br)
.body(bytes))
}).responder()}
@ -306,10 +299,10 @@ fn test_client_streaming_explicit() {
|req: HttpRequest| req.body()
.map_err(Error::from)
.and_then(|body| {
Ok(httpcodes::HttpOk.build()
Ok(HttpResponse::Ok()
.chunked()
.content_encoding(http::ContentEncoding::Identity)
.body(body)?)})
.body(body))})
.responder()));
let body = once(Ok(Bytes::from_static(STR.as_ref())));
@ -328,7 +321,7 @@ fn test_body_streaming_implicit() {
let mut srv = test::TestServer::new(
|app| app.handler(|_| {
let body = once(Ok(Bytes::from_static(STR.as_ref())));
httpcodes::HttpOk.build()
HttpResponse::Ok()
.content_encoding(http::ContentEncoding::Gzip)
.body(Body::Streaming(Box::new(body)))}));
@ -378,8 +371,7 @@ fn test_client_cookie_handling() {
Err(err())
})
// Send some cookies back
.map(|_|
httpcodes::HttpOk.build()
.map(|_| HttpResponse::Ok()
.cookie(cookie1.clone())
.cookie(cookie2.clone())
.finish()

View File

@ -65,7 +65,9 @@ fn test_start() {
let sys = System::new("test");
let srv = HttpServer::new(
|| vec![Application::new()
.resource("/", |r| r.method(http::Method::GET).h(httpcodes::HttpOk))]);
.resource(
"/", |r| r.method(http::Method::GET)
.f(|_|HttpResponse::Ok()))]);
let srv = srv.bind("127.0.0.1:0").unwrap();
let addr = srv.addrs()[0];
@ -108,7 +110,8 @@ fn test_shutdown() {
let sys = System::new("test");
let srv = HttpServer::new(
|| vec![Application::new()
.resource("/", |r| r.method(http::Method::GET).h(httpcodes::HttpOk))]);
.resource(
"/", |r| r.method(http::Method::GET).f(|_| HttpResponse::Ok()))]);
let srv = srv.bind("127.0.0.1:0").unwrap();
let addr = srv.addrs()[0];
@ -133,7 +136,7 @@ fn test_shutdown() {
#[test]
fn test_simple() {
let mut srv = test::TestServer::new(|app| app.handler(httpcodes::HttpOk));
let mut srv = test::TestServer::new(|app| app.handler(|_| HttpResponse::Ok()));
let req = srv.get().finish().unwrap();
let response = srv.execute(req.send()).unwrap();
assert!(response.status().is_success());
@ -147,7 +150,7 @@ fn test_headers() {
move |app| {
let data = srv_data.clone();
app.handler(move |_| {
let mut builder = httpcodes::HttpOk.build();
let mut builder = HttpResponse::Ok();
for idx in 0..90 {
builder.header(
format!("X-TEST-{}", idx).as_str(),
@ -180,7 +183,7 @@ fn test_headers() {
#[test]
fn test_body() {
let mut srv = test::TestServer::new(
|app| app.handler(|_| httpcodes::HttpOk.build().body(STR)));
|app| app.handler(|_| HttpResponse::Ok().body(STR)));
let request = srv.get().finish().unwrap();
let response = srv.execute(request.send()).unwrap();
@ -195,7 +198,7 @@ fn test_body() {
fn test_body_gzip() {
let mut srv = test::TestServer::new(
|app| app.handler(
|_| httpcodes::HttpOk.build()
|_| HttpResponse::Ok()
.content_encoding(http::ContentEncoding::Gzip)
.body(STR)));
@ -222,7 +225,7 @@ fn test_body_gzip_large() {
move |app| {
let data = srv_data.clone();
app.handler(
move |_| httpcodes::HttpOk.build()
move |_| HttpResponse::Ok()
.content_encoding(http::ContentEncoding::Gzip)
.body(data.as_ref()))});
@ -252,7 +255,7 @@ fn test_body_gzip_large_random() {
move |app| {
let data = srv_data.clone();
app.handler(
move |_| httpcodes::HttpOk.build()
move |_| HttpResponse::Ok()
.content_encoding(http::ContentEncoding::Gzip)
.body(data.as_ref()))});
@ -276,7 +279,7 @@ fn test_body_chunked_implicit() {
let mut srv = test::TestServer::new(
|app| app.handler(|_| {
let body = once(Ok(Bytes::from_static(STR.as_ref())));
httpcodes::HttpOk.build()
HttpResponse::Ok()
.content_encoding(http::ContentEncoding::Gzip)
.body(Body::Streaming(Box::new(body)))}));
@ -300,7 +303,7 @@ fn test_body_br_streaming() {
let mut srv = test::TestServer::new(
|app| app.handler(|_| {
let body = once(Ok(Bytes::from_static(STR.as_ref())));
httpcodes::HttpOk.build()
HttpResponse::Ok()
.content_encoding(http::ContentEncoding::Br)
.body(Body::Streaming(Box::new(body)))}));
@ -322,7 +325,7 @@ fn test_body_br_streaming() {
fn test_head_empty() {
let mut srv = test::TestServer::new(
|app| app.handler(|_| {
httpcodes::HttpOk.build()
HttpResponse::Ok()
.content_length(STR.len() as u64).finish()}));
let request = srv.head().finish().unwrap();
@ -343,7 +346,7 @@ fn test_head_empty() {
fn test_head_binary() {
let mut srv = test::TestServer::new(
|app| app.handler(|_| {
httpcodes::HttpOk.build()
HttpResponse::Ok()
.content_encoding(http::ContentEncoding::Identity)
.content_length(100).body(STR)}));
@ -365,7 +368,7 @@ fn test_head_binary() {
fn test_head_binary2() {
let mut srv = test::TestServer::new(
|app| app.handler(|_| {
httpcodes::HttpOk.build()
HttpResponse::Ok()
.content_encoding(http::ContentEncoding::Identity)
.body(STR)
}));
@ -385,7 +388,7 @@ fn test_body_length() {
let mut srv = test::TestServer::new(
|app| app.handler(|_| {
let body = once(Ok(Bytes::from_static(STR.as_ref())));
httpcodes::HttpOk.build()
HttpResponse::Ok()
.content_length(STR.len() as u64)
.content_encoding(http::ContentEncoding::Identity)
.body(Body::Streaming(Box::new(body)))}));
@ -404,7 +407,7 @@ fn test_body_chunked_explicit() {
let mut srv = test::TestServer::new(
|app| app.handler(|_| {
let body = once(Ok(Bytes::from_static(STR.as_ref())));
httpcodes::HttpOk.build()
HttpResponse::Ok()
.chunked()
.content_encoding(http::ContentEncoding::Gzip)
.body(Body::Streaming(Box::new(body)))}));
@ -427,8 +430,7 @@ fn test_body_chunked_explicit() {
fn test_body_deflate() {
let mut srv = test::TestServer::new(
|app| app.handler(
|_| httpcodes::HttpOk
.build()
|_| HttpResponse::Ok()
.content_encoding(http::ContentEncoding::Deflate)
.body(STR)));
@ -452,8 +454,7 @@ fn test_body_deflate() {
fn test_body_brotli() {
let mut srv = test::TestServer::new(
|app| app.handler(
|_| httpcodes::HttpOk
.build()
|_| HttpResponse::Ok()
.content_encoding(http::ContentEncoding::Br)
.body(STR)));
@ -477,8 +478,7 @@ fn test_gzip_encoding() {
let mut srv = test::TestServer::new(|app| app.handler(|req: HttpRequest| {
req.body()
.and_then(|bytes: Bytes| {
Ok(httpcodes::HttpOk
.build()
Ok(HttpResponse::Ok()
.content_encoding(http::ContentEncoding::Identity)
.body(bytes))
}).responder()}
@ -506,8 +506,7 @@ fn test_gzip_encoding_large() {
let mut srv = test::TestServer::new(|app| app.handler(|req: HttpRequest| {
req.body()
.and_then(|bytes: Bytes| {
Ok(httpcodes::HttpOk
.build()
Ok(HttpResponse::Ok()
.content_encoding(http::ContentEncoding::Identity)
.body(bytes))
}).responder()}
@ -539,8 +538,7 @@ fn test_reading_gzip_encoding_large_random() {
let mut srv = test::TestServer::new(|app| app.handler(|req: HttpRequest| {
req.body()
.and_then(|bytes: Bytes| {
Ok(httpcodes::HttpOk
.build()
Ok(HttpResponse::Ok()
.content_encoding(http::ContentEncoding::Identity)
.body(bytes))
}).responder()}
@ -568,8 +566,7 @@ fn test_reading_deflate_encoding() {
let mut srv = test::TestServer::new(|app| app.handler(|req: HttpRequest| {
req.body()
.and_then(|bytes: Bytes| {
Ok(httpcodes::HttpOk
.build()
Ok(HttpResponse::Ok()
.content_encoding(http::ContentEncoding::Identity)
.body(bytes))
}).responder()}
@ -597,8 +594,7 @@ fn test_reading_deflate_encoding_large() {
let mut srv = test::TestServer::new(|app| app.handler(|req: HttpRequest| {
req.body()
.and_then(|bytes: Bytes| {
Ok(httpcodes::HttpOk
.build()
Ok(HttpResponse::Ok()
.content_encoding(http::ContentEncoding::Identity)
.body(bytes))
}).responder()}
@ -630,8 +626,7 @@ fn test_reading_deflate_encoding_large_random() {
let mut srv = test::TestServer::new(|app| app.handler(|req: HttpRequest| {
req.body()
.and_then(|bytes: Bytes| {
Ok(httpcodes::HttpOk
.build()
Ok(HttpResponse::Ok()
.content_encoding(http::ContentEncoding::Identity)
.body(bytes))
}).responder()}
@ -660,8 +655,7 @@ fn test_brotli_encoding() {
let mut srv = test::TestServer::new(|app| app.handler(|req: HttpRequest| {
req.body()
.and_then(|bytes: Bytes| {
Ok(httpcodes::HttpOk
.build()
Ok(HttpResponse::Ok()
.content_encoding(http::ContentEncoding::Identity)
.body(bytes))
}).responder()}
@ -690,8 +684,7 @@ fn test_brotli_encoding_large() {
let mut srv = test::TestServer::new(|app| app.handler(|req: HttpRequest| {
req.body()
.and_then(|bytes: Bytes| {
Ok(httpcodes::HttpOk
.build()
Ok(HttpResponse::Ok()
.content_encoding(http::ContentEncoding::Identity)
.body(bytes))
}).responder()}
@ -716,7 +709,7 @@ fn test_brotli_encoding_large() {
#[test]
fn test_h2() {
let srv = test::TestServer::new(|app| app.handler(|_|{
httpcodes::HttpOk.build().body(STR)
HttpResponse::Ok().body(STR)
}));
let addr = srv.addr();
@ -756,7 +749,7 @@ fn test_h2() {
#[test]
fn test_application() {
let mut srv = test::TestServer::with_factory(
|| Application::new().resource("/", |r| r.h(httpcodes::HttpOk)));
|| Application::new().resource("/", |r| r.f(|_| HttpResponse::Ok())));
let request = srv.get().finish().unwrap();
let response = srv.execute(request.send()).unwrap();
@ -800,7 +793,7 @@ fn test_middlewares() {
move |app| app.middleware(MiddlewareTest{start: Arc::clone(&act_num1),
response: Arc::clone(&act_num2),
finish: Arc::clone(&act_num3)})
.handler(httpcodes::HttpOk)
.handler(|_| HttpResponse::Ok())
);
let request = srv.get().finish().unwrap();
@ -824,11 +817,11 @@ fn test_resource_middlewares() {
let act_num3 = Arc::clone(&num3);
let mut srv = test::TestServer::new(
move |app| app.handler2(
httpcodes::HttpOk,
MiddlewareTest{start: Arc::clone(&act_num1),
move |app| app
.middleware(MiddlewareTest{start: Arc::clone(&act_num1),
response: Arc::clone(&act_num2),
finish: Arc::clone(&act_num3)})
.handler(|_| HttpResponse::Ok())
);
let request = srv.get().finish().unwrap();