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

View File

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

View File

@ -1,4 +1,4 @@
use actix_web::*; use actix_web::{Error, HttpMessage, HttpResponse, HttpRequest};
use futures::Future; use futures::Future;
@ -14,6 +14,6 @@ pub fn info(req: HttpRequest) -> Box<Future<Item=HttpResponse, Error=Error>> {
req.json() req.json()
.from_err() .from_err()
.and_then(|res: Info| { .and_then(|res: Info| {
Ok(httpcodes::HttpOk.build().json(res)?) Ok(HttpResponse::Ok().json(res))
}).responder() }).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 http;
# extern crate actix_web; # extern crate actix_web;
use http::{header, HttpTryFrom}; 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}; use actix_web::middleware::{Middleware, Started, Response};
struct Headers; // <- Our middleware struct Headers; // <- Our middleware
@ -53,7 +53,7 @@ impl<S> Middleware<S> for Headers {
fn main() { fn main() {
Application::new() Application::new()
.middleware(Headers) // <- Register middleware, this method can be called multiple times .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 ```rust
# extern crate actix_web; # extern crate actix_web;
use actix_web::{Application, http, httpcodes, middleware}; use actix_web::{http, middleware, Application, HttpResponse};
fn main() { fn main() {
let app = Application::new() let app = Application::new()
@ -144,8 +144,8 @@ fn main() {
.header("X-Version", "0.2") .header("X-Version", "0.2")
.finish()) .finish())
.resource("/test", |r| { .resource("/test", |r| {
r.method(http::Method::GET).f(|req| httpcodes::HttpOk); r.method(http::Method::GET).f(|req| HttpResponse::Ok());
r.method(http::Method::HEAD).f(|req| httpcodes::HttpMethodNotAllowed); r.method(http::Method::HEAD).f(|req| HttpResponse::MethodNotAllowed());
}) })
.finish(); .finish();
} }

View File

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

View File

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

View File

@ -19,7 +19,7 @@ but path `/application` would not match.
```rust,ignore ```rust,ignore
# extern crate actix_web; # extern crate actix_web;
# extern crate tokio_core; # extern crate tokio_core;
# use actix_web::*; # use actix_web::{*, http::Method};
# fn index(req: HttpRequest) -> &'static str { # fn index(req: HttpRequest) -> &'static str {
# "Hello world!" # "Hello world!"
# } # }
@ -43,18 +43,18 @@ Multiple applications can be served with one server:
# extern crate tokio_core; # extern crate tokio_core;
# use tokio_core::net::TcpStream; # use tokio_core::net::TcpStream;
# use std::net::SocketAddr; # use std::net::SocketAddr;
use actix_web::*; use actix_web::{Application, HttpResponse, HttpServer};
fn main() { fn main() {
HttpServer::new(|| vec![ HttpServer::new(|| vec![
Application::new() Application::new()
.prefix("/app1") .prefix("/app1")
.resource("/", |r| r.f(|r| httpcodes::HttpOk)), .resource("/", |r| r.f(|r| HttpResponse::Ok())),
Application::new() Application::new()
.prefix("/app2") .prefix("/app2")
.resource("/", |r| r.f(|r| httpcodes::HttpOk)), .resource("/", |r| r.f(|r| HttpResponse::Ok())),
Application::new() 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;
# extern crate actix_web; # extern crate actix_web;
use actix::*; use actix::*;
use actix_web::*; use actix_web::{server, Application, HttpResponse};
fn main() { fn main() {
let sys = actix::System::new("guide"); let sys = actix::System::new("guide");
HttpServer::new( server::new(
|| Application::new() || Application::new()
.resource("/", |r| r.h(httpcodes::HttpOk))) .resource("/", |r| r.f(|_| HttpResponse::Ok())))
.bind("127.0.0.1:59080").unwrap() .bind("127.0.0.1:59080").unwrap()
.start(); .start();
@ -46,18 +46,19 @@ address of the started http server. Actix http server accepts several messages:
# extern crate actix; # extern crate actix;
# extern crate actix_web; # extern crate actix_web;
# use futures::Future; # use futures::Future;
use actix_web::*;
use std::thread; use std::thread;
use std::sync::mpsc; use std::sync::mpsc;
use actix::*;
use actix_web::{server, Application, HttpResponse, HttpServer};
fn main() { fn main() {
let (tx, rx) = mpsc::channel(); let (tx, rx) = mpsc::channel();
thread::spawn(move || { thread::spawn(move || {
let sys = actix::System::new("http-server"); let sys = actix::System::new("http-server");
let addr = HttpServer::new( let addr = server::new(
|| Application::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") .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 .shutdown_timeout(60) // <- Set shutdown timeout to 60 seconds
.start(); .start();
@ -80,12 +81,12 @@ can be overridden with the `HttpServer::threads()` method.
```rust ```rust
# extern crate actix_web; # extern crate actix_web;
# extern crate tokio_core; # extern crate tokio_core;
use actix_web::*; use actix_web::{Application, HttpServer, HttpResponse};
fn main() { fn main() {
HttpServer::new( HttpServer::new(
|| Application::new() || Application::new()
.resource("/", |r| r.h(httpcodes::HttpOk))) .resource("/", |r| r.f(|_| HttpResponse::Ok())))
.threads(4); // <- Start 4 workers .threads(4); // <- Start 4 workers
} }
``` ```
@ -109,16 +110,16 @@ use std::fs::File;
use actix_web::*; use actix_web::*;
fn main() { fn main() {
let mut file = File::open("identity.pfx").unwrap(); // load ssl keys
let mut pkcs12 = vec![]; let mut builder = SslAcceptor::mozilla_intermediate(SslMethod::tls()).unwrap();
file.read_to_end(&mut pkcs12).unwrap(); builder.set_private_key_file("key.pem", SslFiletype::PEM).unwrap();
let pkcs12 = Pkcs12::from_der(&pkcs12).unwrap().parse("12345").unwrap(); builder.set_certificate_chain_file("cert.pem").unwrap();
HttpServer::new( HttpServer::new(
|| Application::new() || Application::new()
.resource("/index.html", |r| r.f(index))) .resource("/index.html", |r| r.f(index)))
.bind("127.0.0.1:8080").unwrap() .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 ```rust
# extern crate actix_web; # extern crate actix_web;
# extern crate tokio_core; # extern crate tokio_core;
use actix_web::*; use actix_web::{server, Application, HttpResponse};
fn main() { fn main() {
HttpServer::new(|| server::new(||
Application::new() Application::new()
.resource("/", |r| r.h(httpcodes::HttpOk))) .resource("/", |r| r.f(|_| HttpResponse::Ok())))
.keep_alive(75); // <- Set keep-alive to 75 seconds .keep_alive(75); // <- Set keep-alive to 75 seconds
HttpServer::new(|| server::new(||
Application::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. .keep_alive(server::KeepAlive::Tcp(75)); // <- Use `SO_KEEPALIVE` socket option.
HttpServer::new(|| server::new(||
Application::new() Application::new()
.resource("/", |r| r.h(httpcodes::HttpOk))) .resource("/", |r| r.f(|_| HttpResponse::Ok())))
.keep_alive(None); // <- Disable keep-alive .keep_alive(None); // <- Disable keep-alive
} }
``` ```
@ -172,13 +173,13 @@ and is on for *HTTP/1.1* and *HTTP/2.0*.
```rust ```rust
# extern crate actix_web; # extern crate actix_web;
use actix_web::{HttpRequest, HttpResponse, http, httpcodes::HttpOk}; use actix_web::{HttpRequest, HttpResponse, http};
fn index(req: HttpRequest) -> HttpResponse { fn index(req: HttpRequest) -> HttpResponse {
HttpOk.build() HttpResponse::Ok()
.connection_type(http::ConnectionType::Close) // <- Close connection .connection_type(http::ConnectionType::Close) // <- Close connection
.force_close() // <- Alternative method .force_close() // <- Alternative method
.finish().unwrap() .finish()
} }
# fn main() {} # 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: Here is an example of a handler that stores the number of processed requests:
```rust ```rust
# extern crate actix;
# extern crate actix_web; # extern crate actix_web;
use actix_web::*; use actix_web::{Application, HttpRequest, HttpResponse, dev::Handler};
use actix_web::dev::Handler;
struct MyHandler(usize); struct MyHandler(usize);
@ -65,7 +63,7 @@ impl<S> Handler<S> for MyHandler {
/// Handle request /// Handle request
fn handle(&mut self, req: HttpRequest<S>) -> Self::Result { fn handle(&mut self, req: HttpRequest<S>) -> Self::Result {
self.0 += 1; self.0 += 1;
httpcodes::HttpOk.into() HttpResponse::Ok().into()
} }
} }
# fn main() {} # fn main() {}
@ -77,8 +75,7 @@ number of requests processed per thread. A proper implementation would use `Arc`
```rust ```rust
# extern crate actix; # extern crate actix;
# extern crate actix_web; # extern crate actix_web;
use actix_web::*; use actix_web::{server, Application, HttpRequest, HttpResponse, dev::Handler};
use actix_web::dev::Handler;
use std::sync::Arc; use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::atomic::{AtomicUsize, Ordering};
@ -90,7 +87,7 @@ impl<S> Handler<S> for MyHandler {
/// Handle request /// Handle request
fn handle(&mut self, req: HttpRequest<S>) -> Self::Result { fn handle(&mut self, req: HttpRequest<S>) -> Self::Result {
self.0.fetch_add(1, Ordering::Relaxed); 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)); let inc = Arc::new(AtomicUsize::new(0));
HttpServer::new( server::new(
move || { move || {
let cloned = inc.clone(); let cloned = inc.clone();
Application::new() Application::new()
@ -148,7 +145,7 @@ impl Responder for MyObj {
// Create response and set content type // Create response and set content type
Ok(HttpResponse::Ok() Ok(HttpResponse::Ok()
.content_type("application/json") .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}; # use futures::future::{Future, result};
fn index(req: HttpRequest) -> Box<Future<Item=HttpResponse, Error=Error>> { fn index(req: HttpRequest) -> Box<Future<Item=HttpResponse, Error=Error>> {
result(HttpResponse::Ok() result(Ok(HttpResponse::Ok()
.content_type("text/html") .content_type("text/html")
.body(format!("Hello!")) .body(format!("Hello!"))))
.map_err(|e| e.into()))
.responder() .responder()
} }
@ -224,7 +220,7 @@ fn index(req: HttpRequest) -> HttpResponse {
HttpResponse::Ok() HttpResponse::Ok()
.content_type("application/json") .content_type("application/json")
.body(Body::Streaming(Box::new(body))).unwrap() .body(Body::Streaming(Box::new(body)))
} }
fn main() { fn main() {
@ -253,9 +249,9 @@ fn index(req: HttpRequest) -> Result<Box<Future<Item=HttpResponse, Error=Error>>
Err(error::ErrorBadRequest("bad request")) Err(error::ErrorBadRequest("bad request"))
} else { } else {
Ok(Box::new( Ok(Box::new(
result(HttpResponse::Ok() result(Ok(HttpResponse::Ok()
.content_type("text/html") .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 actix_web::*;
# use futures::future::Future; # use futures::future::Future;
use futures::future::result; 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>>>; type RegisterResult = Either<HttpResponse, Box<Future<Item=HttpResponse, Error=Error>>>;
fn index(req: HttpRequest) -> RegisterResult { fn index(req: HttpRequest) -> RegisterResult {
if is_a_variant() { // <- choose variant A if is_a_variant() { // <- choose variant A
Either::A( Either::A(
httpcodes::HttpBadRequest.with_body("Bad data")) HttpResponse::BadRequest().body("Bad data"))
} else { } else {
Either::B( // <- variant B Either::B( // <- variant B
result(HttpResponse::Ok() result(Ok(HttpResponse::Ok()
.content_type("text/html") .content_type("text/html")
.body(format!("Hello!")) .body(format!("Hello!")))).responder())
.map_err(|e| e.into())).responder())
} }
} }
# fn is_a_variant() -> bool { true } # fn is_a_variant() -> bool { true }

View File

@ -70,7 +70,7 @@ to return different responses for different types of errors.
```rust ```rust
# extern crate actix_web; # extern crate actix_web;
#[macro_use] extern crate failure; #[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)] #[derive(Fail, Debug)]
enum MyError { enum MyError {
@ -86,11 +86,11 @@ impl error::ResponseError for MyError {
fn error_response(&self) -> HttpResponse { fn error_response(&self) -> HttpResponse {
match *self { match *self {
MyError::InternalError => HttpResponse::new( MyError::InternalError => HttpResponse::new(
http::StatusCode::INTERNAL_SERVER_ERROR, Body::Empty), http::StatusCode::INTERNAL_SERVER_ERROR),
MyError::BadClientData => HttpResponse::new( MyError::BadClientData => HttpResponse::new(
http::StatusCode::BAD_REQUEST, Body::Empty), http::StatusCode::BAD_REQUEST),
MyError::Timeout => HttpResponse::new( 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 ```rust
# extern crate actix_web; # extern crate actix_web;
# use actix_web::{Application, HttpRequest, HttpResponse, http::Method}; # use actix_web::{Application, HttpRequest, HttpResponse, http::Method};
# use actix_web::httpcodes::HttpOk;
# #
# fn index(req: HttpRequest) -> HttpResponse { # fn index(req: HttpRequest) -> HttpResponse {
# unimplemented!() # unimplemented!()
@ -32,7 +31,7 @@ fn main() {
Application::new() Application::new()
.resource("/prefix", |r| r.f(index)) .resource("/prefix", |r| r.f(index))
.resource("/user/{name}", .resource("/user/{name}",
|r| r.method(Method::GET).f(|req| HttpOk)) |r| r.method(Method::GET).f(|req| HttpResponse::Ok()))
.finish(); .finish();
} }
``` ```
@ -62,7 +61,6 @@ any number of *predicates* but only one handler.
```rust ```rust
# extern crate actix_web; # extern crate actix_web;
# use actix_web::*; # use actix_web::*;
# use actix_web::httpcodes::*;
fn main() { fn main() {
Application::new() Application::new()
@ -70,13 +68,13 @@ fn main() {
resource.route() resource.route()
.filter(pred::Get()) .filter(pred::Get())
.filter(pred::Header("content-type", "text/plain")) .filter(pred::Header("content-type", "text/plain"))
.f(|req| HttpOk) .f(|req| HttpResponse::Ok())
) )
.finish(); .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* 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. 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. 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 ```rust
# extern crate actix_web; # extern crate actix_web;
# use actix_web::{Application, HttpRequest, HttpResponse, http::Method}; # use actix_web::{Application, HttpRequest, HttpResponse, http::Method};
# use actix_web::httpcodes::HttpOk;
# #
fn index(req: HttpRequest) -> HttpResponse { fn index(req: HttpRequest) -> HttpResponse {
let url = req.url_for("foo", &["1", "2", "3"]); // <- generate url for "foo" resource let url = req.url_for("foo", &["1", "2", "3"]); // <- generate url for "foo" resource
HttpOk.into() HttpResponse::Ok().into()
} }
fn main() { fn main() {
let app = Application::new() let app = Application::new()
.resource("/test/{a}/{b}/{c}", |r| { .resource("/test/{a}/{b}/{c}", |r| {
r.name("foo"); // <- set resource name, then it could be used in `url_for` 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(); .finish();
} }
@ -397,12 +394,12 @@ for URL generation purposes only and are never considered for matching at reques
```rust ```rust
# extern crate actix_web; # 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"])?; let url = req.url_for("youtube", &["oHg5SJYRHA0"])?;
assert_eq!(url.as_str(), "https://youtube.com/watch/oHg5SJYRHA0"); assert_eq!(url.as_str(), "https://youtube.com/watch/oHg5SJYRHA0");
Ok(httpcodes::HttpOk.into()) Ok(HttpResponse::Ok().into())
} }
fn main() { 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::*;
use actix_web::http::NormalizePath; use actix_web::http::NormalizePath;
# #
# fn index(req: HttpRequest) -> httpcodes::StaticResponse { # fn index(req: HttpRequest) -> HttpResponse {
# httpcodes::HttpOk # HttpResponse::Ok().into()
# } # }
fn main() { fn main() {
let app = Application::new() let app = Application::new()
@ -462,10 +459,10 @@ It is possible to register path normalization only for *GET* requests only:
```rust ```rust
# extern crate actix_web; # extern crate actix_web;
# #[macro_use] extern crate serde_derive; # #[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 { # fn index(req: HttpRequest) -> &'static str {
# httpcodes::HttpOk # "test"
# } # }
fn main() { fn main() {
let app = Application::new() let app = Application::new()
@ -519,18 +516,15 @@ Here is a simple predicate that check that a request contains a specific *header
```rust ```rust
# extern crate actix_web; # extern crate actix_web;
# extern crate http;
# use actix_web::*; # use actix_web::*;
# use actix_web::httpcodes::*; use actix_web::{http, pred::Predicate, Application, HttpRequest};
use http::header::CONTENT_TYPE;
use actix_web::pred::Predicate;
struct ContentTypeHeader; struct ContentTypeHeader;
impl<S: 'static> Predicate<S> for ContentTypeHeader { impl<S: 'static> Predicate<S> for ContentTypeHeader {
fn check(&self, req: &mut HttpRequest<S>) -> bool { 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| .resource("/index.html", |r|
r.route() r.route()
.filter(ContentTypeHeader) .filter(ContentTypeHeader)
.h(HttpOk)); .f(|_| HttpResponse::Ok()));
} }
``` ```
@ -559,15 +553,14 @@ except "GET":
# extern crate actix_web; # extern crate actix_web;
# extern crate http; # extern crate http;
# use actix_web::*; # use actix_web::*;
# use actix_web::httpcodes::*; use actix_web::{pred, Application, HttpResponse};
use actix_web::pred;
fn main() { fn main() {
Application::new() Application::new()
.resource("/index.html", |r| .resource("/index.html", |r|
r.route() r.route()
.filter(pred::Not(pred::Get())) .filter(pred::Not(pred::Get()))
.f(|req| HttpMethodNotAllowed)) .f(|req| HttpResponse::MethodNotAllowed()))
.finish(); .finish();
} }
``` ```
@ -596,14 +589,14 @@ with `Application::resource()` method.
```rust ```rust
# extern crate actix_web; # extern crate actix_web;
use actix_web::{Application, http::Method, pred}; use actix_web::{Application, HttpResponse, http::Method, pred};
use actix_web::httpcodes::{HttpNotFound, HttpMethodNotAllowed};
fn main() { fn main() {
Application::new() Application::new()
.default_resource(|r| { .default_resource(|r| {
r.method(Method::GET).f(|req| HttpNotFound); r.method(Method::GET).f(|req| HttpResponse::NotFound());
r.route().filter(pred::Not(pred::Get())).f(|req| HttpMethodNotAllowed); r.route().filter(pred::Not(pred::Get()))
.f(|req| HttpResponse::MethodNotAllowed());
}) })
# .finish(); # .finish();
} }

View File

@ -19,7 +19,7 @@ fn index(req: HttpRequest) -> HttpResponse {
.content_encoding(ContentEncoding::Br) .content_encoding(ContentEncoding::Br)
.content_type("plain/text") .content_type("plain/text")
.header("X-Hdr", "sample") .header("X-Hdr", "sample")
.body("data").unwrap() .body("data")
} }
# fn main() {} # fn main() {}
``` ```
@ -50,7 +50,7 @@ use actix_web::{HttpRequest, HttpResponse, http::ContentEncoding};
fn index(req: HttpRequest) -> HttpResponse { fn index(req: HttpRequest) -> HttpResponse {
HttpResponse::Ok() HttpResponse::Ok()
.content_encoding(ContentEncoding::Br) .content_encoding(ContentEncoding::Br)
.body("data").unwrap() .body("data")
} }
# fn main() {} # fn main() {}
``` ```
@ -82,7 +82,7 @@ fn index(mut req: HttpRequest) -> Box<Future<Item=HttpResponse, Error=Error>> {
req.json().from_err() req.json().from_err()
.and_then(|val: MyObj| { .and_then(|val: MyObj| {
println!("model: {:?}", val); println!("model: {:?}", val);
Ok(httpcodes::HttpOk.build().json(val)?) // <- send response Ok(HttpResponse::Ok().json(val)) // <- send response
}) })
.responder() .responder()
} }
@ -115,7 +115,7 @@ fn index(req: HttpRequest) -> Box<Future<Item=HttpResponse, Error=Error>> {
// synchronous workflow // synchronous workflow
.and_then(|body| { // <- body is loaded, now we can deserialize json .and_then(|body| { // <- body is loaded, now we can deserialize json
let obj = serde_json::from_slice::<MyObj>(&body)?; let obj = serde_json::from_slice::<MyObj>(&body)?;
Ok(httpcodes::HttpOk.build().json(obj)?) // <- send response Ok(HttpResponse::Ok().json(obj)) // <- send response
}) })
.responder() .responder()
} }
@ -178,7 +178,7 @@ use futures::stream::once;
fn index(req: HttpRequest) -> HttpResponse { fn index(req: HttpRequest) -> HttpResponse {
HttpResponse::Ok() HttpResponse::Ok()
.chunked() .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() {} # fn main() {}
``` ```
@ -249,7 +249,7 @@ fn index(mut req: HttpRequest) -> Box<Future<Item=HttpResponse, Error=Error>> {
.from_err() .from_err()
.and_then(|params| { // <- url encoded parameters .and_then(|params| { // <- url encoded parameters
println!("==== BODY ==== {:?}", params); println!("==== BODY ==== {:?}", params);
ok(httpcodes::HttpOk.into()) ok(HttpResponse::Ok().into())
}) })
.responder() .responder()
} }
@ -278,7 +278,7 @@ fn index(mut req: HttpRequest) -> Box<Future<Item=HttpResponse, Error=Error>> {
println!("Chunk: {:?}", chunk); println!("Chunk: {:?}", chunk);
result::<_, error::PayloadError>(Ok(())) result::<_, error::PayloadError>(Ok(()))
}) })
.map(|_| HttpResponse::Ok().finish().unwrap()) .map(|_| HttpResponse::Ok().finish())
.responder() .responder()
} }
# fn main() {} # 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()`. run your handler with `run()` or `run_async()`.
```rust ```rust
# extern crate http;
# extern crate actix_web; # extern crate actix_web;
use http::{header, StatusCode}; use actix_web::{http, test, HttpRequest, HttpResponse, HttpMessage};
use actix_web::*;
use actix_web::test::TestRequest;
fn index(req: HttpRequest) -> HttpResponse { 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() { if let Ok(s) = hdr.to_str() {
return httpcodes::HttpOk.into() return HttpResponse::Ok().into()
} }
} }
httpcodes::HttpBadRequest.into() HttpResponse::BadRequest().into()
} }
fn main() { fn main() {
let resp = TestRequest::with_header("content-type", "text/plain") let resp = test::TestRequest::with_header("content-type", "text/plain")
.run(index) .run(index)
.unwrap(); .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) .run(index)
.unwrap(); .unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST); assert_eq!(resp.status(), http::StatusCode::BAD_REQUEST);
} }
``` ```
@ -55,11 +52,11 @@ for more information.
```rust ```rust
# extern crate actix_web; # extern crate actix_web;
use actix_web::*; use actix_web::{HttpRequest, HttpResponse, HttpMessage};
use actix_web::test::TestServer; use actix_web::test::TestServer;
fn index(req: HttpRequest) -> HttpResponse { fn index(req: HttpRequest) -> HttpResponse {
httpcodes::HttpOk.into() HttpResponse::Ok().into()
} }
fn main() { 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. function same way as you would for real http server configuration.
```rust ```rust
# extern crate http;
# extern crate actix_web; # extern crate actix_web;
use http::Method; use actix_web::{http, test, Application, HttpRequest, HttpResponse};
use actix_web::*;
use actix_web::test::TestServer;
fn index(req: HttpRequest) -> HttpResponse { fn index(req: HttpRequest) -> HttpResponse {
httpcodes::HttpOk.into() HttpResponse::Ok().into()
} }
/// This function get called by http server. /// This function get called by http server.
@ -94,9 +88,10 @@ fn create_app() -> Application {
} }
fn main() { 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 let response = srv.execute(request.send()).unwrap(); // <- send request to the server
assert!(response.status().is_success()); // <- check response assert!(response.status().is_success()); // <- check response

View File

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

View File

@ -20,11 +20,9 @@ pub use url::ParseError as UrlParseError;
// re-exports // re-exports
pub use cookie::{ParseError as CookieParseError}; pub use cookie::{ParseError as CookieParseError};
use body::Body;
use handler::Responder; use handler::Responder;
use httprequest::HttpRequest; use httprequest::HttpRequest;
use httpresponse::HttpResponse; use httpresponse::HttpResponse;
use httpcodes::{self, HttpExpectationFailed};
/// A specialized [`Result`](https://doc.rust-lang.org/std/result/enum.Result.html) /// A specialized [`Result`](https://doc.rust-lang.org/std/result/enum.Result.html)
/// for actix web operations /// for actix web operations
@ -55,7 +53,7 @@ pub trait ResponseError: Fail {
/// ///
/// Internal server error is generated by default. /// Internal server error is generated by default.
fn error_response(&self) -> HttpResponse { 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` /// Return `BAD_REQUEST` for `de::value::Error`
impl ResponseError for DeError { impl ResponseError for DeError {
fn error_response(&self) -> HttpResponse { 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 { fn error_response(&self) -> HttpResponse {
match self.kind() { match self.kind() {
io::ErrorKind::NotFound => io::ErrorKind::NotFound =>
HttpResponse::new(StatusCode::NOT_FOUND, Body::Empty), HttpResponse::new(StatusCode::NOT_FOUND),
io::ErrorKind::PermissionDenied => 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` /// `BadRequest` for `InvalidHeaderValue`
impl ResponseError for header::InvalidHeaderValue { impl ResponseError for header::InvalidHeaderValue {
fn error_response(&self) -> HttpResponse { fn error_response(&self) -> HttpResponse {
HttpResponse::new(StatusCode::BAD_REQUEST, Body::Empty) HttpResponse::new(StatusCode::BAD_REQUEST)
} }
} }
/// `BadRequest` for `InvalidHeaderValue` /// `BadRequest` for `InvalidHeaderValue`
impl ResponseError for header::InvalidHeaderValueBytes { impl ResponseError for header::InvalidHeaderValueBytes {
fn error_response(&self) -> HttpResponse { fn error_response(&self) -> HttpResponse {
HttpResponse::new(StatusCode::BAD_REQUEST, Body::Empty) HttpResponse::new(StatusCode::BAD_REQUEST)
} }
} }
@ -195,7 +193,7 @@ pub enum ParseError {
/// Return `BadRequest` for `ParseError` /// Return `BadRequest` for `ParseError`
impl ResponseError for ParseError { impl ResponseError for ParseError {
fn error_response(&self) -> HttpResponse { fn error_response(&self) -> 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` /// Return `BadRequest` for `cookie::ParseError`
impl ResponseError for cookie::ParseError { impl ResponseError for cookie::ParseError {
fn error_response(&self) -> HttpResponse { 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` /// Return `BadRequest` for `HttpRangeError`
impl ResponseError for HttpRangeError { impl ResponseError for HttpRangeError {
fn error_response(&self) -> HttpResponse { fn error_response(&self) -> HttpResponse {
HttpResponse::new( HttpResponse::with_body(
StatusCode::BAD_REQUEST, Body::from("Invalid Range header provided")) StatusCode::BAD_REQUEST, "Invalid Range header provided")
} }
} }
@ -343,7 +341,7 @@ impl From<PayloadError> for MultipartError {
impl ResponseError for MultipartError { impl ResponseError for MultipartError {
fn error_response(&self) -> HttpResponse { 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 { impl ResponseError for ExpectError {
fn error_response(&self) -> HttpResponse { 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` /// Return `BadRequest` for `ContentTypeError`
impl ResponseError for ContentTypeError { impl ResponseError for ContentTypeError {
fn error_response(&self) -> HttpResponse { 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 { fn error_response(&self) -> HttpResponse {
match *self { match *self {
UrlencodedError::Overflow => httpcodes::HttpPayloadTooLarge.into(), UrlencodedError::Overflow =>
UrlencodedError::UnknownLength => httpcodes::HttpLengthRequired.into(), HttpResponse::new(StatusCode::PAYLOAD_TOO_LARGE),
_ => httpcodes::HttpBadRequest.into(), 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 { fn error_response(&self) -> HttpResponse {
match *self { match *self {
JsonPayloadError::Overflow => httpcodes::HttpPayloadTooLarge.into(), JsonPayloadError::Overflow =>
_ => httpcodes::HttpBadRequest.into(), HttpResponse::new(StatusCode::PAYLOAD_TOO_LARGE),
_ =>
HttpResponse::new(StatusCode::BAD_REQUEST),
} }
} }
} }
@ -482,7 +485,7 @@ pub enum UriSegmentError {
impl ResponseError for UriSegmentError { impl ResponseError for UriSegmentError {
fn error_response(&self) -> HttpResponse { 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 where T: Send + Sync + fmt::Debug + 'static
{ {
fn error_response(&self) -> HttpResponse { 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 std::os::unix::fs::MetadataExt;
use bytes::{Bytes, BytesMut, BufMut}; use bytes::{Bytes, BytesMut, BufMut};
use http::{Method, StatusCode};
use futures::{Async, Poll, Future, Stream}; use futures::{Async, Poll, Future, Stream};
use futures_cpupool::{CpuPool, CpuFuture}; use futures_cpupool::{CpuPool, CpuFuture};
use mime_guess::get_mime_type; use mime_guess::get_mime_type;
@ -22,10 +21,10 @@ use header;
use error::Error; use error::Error;
use param::FromParam; use param::FromParam;
use handler::{Handler, RouteHandler, WrapHandler, Responder, Reply}; use handler::{Handler, RouteHandler, WrapHandler, Responder, Reply};
use http::{Method, StatusCode};
use httpmessage::HttpMessage; use httpmessage::HttpMessage;
use httprequest::HttpRequest; use httprequest::HttpRequest;
use httpresponse::HttpResponse; use httpresponse::HttpResponse;
use httpcodes::{HttpOk, HttpFound, HttpNotFound, HttpMethodNotAllowed};
/// A file with an associated name; responds with the Content-Type based on the /// A file with an associated name; responds with the Content-Type based on the
/// file extension. /// file extension.
@ -177,10 +176,10 @@ impl Responder for NamedFile {
fn respond_to(self, req: HttpRequest) -> Result<HttpResponse, io::Error> { fn respond_to(self, req: HttpRequest) -> Result<HttpResponse, io::Error> {
if self.only_get && *req.method() != Method::GET && *req.method() != Method::HEAD { 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::CONTENT_TYPE, "text/plain")
.header(header::ALLOW, "GET, HEAD") .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(); let etag = self.etag();
@ -208,7 +207,7 @@ impl Responder for NamedFile {
false false
}; };
let mut resp = HttpOk.build(); let mut resp = HttpResponse::Ok();
resp resp
.if_some(self.path().extension(), |ext, 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_some(etag, |etag, resp| {resp.set(header::ETag(etag));});
if precondition_failed { if precondition_failed {
return Ok(resp.status(StatusCode::PRECONDITION_FAILED).finish().unwrap()) return Ok(resp.status(StatusCode::PRECONDITION_FAILED).finish())
} else if not_modified { } 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 { if *req.method() == Method::HEAD {
Ok(resp.finish().unwrap()) Ok(resp.finish())
} else { } else {
let reader = ChunkedReadFile { let reader = ChunkedReadFile {
size: self.md.len(), size: self.md.len(),
@ -233,7 +232,7 @@ impl Responder for NamedFile {
file: Some(self.file), file: Some(self.file),
fut: None, fut: None,
}; };
Ok(resp.streaming(reader).unwrap()) Ok(resp.streaming(reader))
} }
} }
} }
@ -356,9 +355,9 @@ impl Responder for Directory {
<ul>\ <ul>\
{}\ {}\
</ul></body>\n</html>", index_of, index_of, body); </ul></body>\n</html>", index_of, index_of, body);
Ok(HttpOk.build() Ok(HttpResponse::Ok()
.content_type("text/html; charset=utf-8") .content_type("text/html; charset=utf-8")
.body(html).unwrap()) .body(html))
} }
} }
@ -418,7 +417,8 @@ impl<S: 'static> StaticFiles<S> {
index: None, index: None,
show_index: index, show_index: index,
cpu_pool: CpuPool::new(40), cpu_pool: CpuPool::new(40),
default: Box::new(WrapHandler::new(|_| HttpNotFound)), default: Box::new(WrapHandler::new(
|_| HttpResponse::new(StatusCode::NOT_FOUND))),
_chunk_size: 0, _chunk_size: 0,
_follow_symlinks: false, _follow_symlinks: false,
} }
@ -465,9 +465,9 @@ impl<S: 'static> Handler<S> for StaticFiles<S> {
new_path.push('/'); new_path.push('/');
} }
new_path.push_str(redir_index); new_path.push_str(redir_index);
HttpFound.build() HttpResponse::Found()
.header(header::LOCATION, new_path.as_str()) .header(header::LOCATION, new_path.as_str())
.finish().unwrap() .finish()
.respond_to(req.without_state()) .respond_to(req.without_state())
} else if self.show_index { } else if self.show_index {
Directory::new(self.directory.clone(), path) 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 actix_web;
/// # extern crate futures; /// # extern crate futures;
/// # use futures::future::Future; /// # use futures::future::Future;
/// use actix_web::AsyncResponder;
/// use futures::future::result; /// 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>>>; /// 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 { /// fn index(req: HttpRequest) -> RegisterResult {
/// if is_a_variant() { // <- choose variant A /// if is_a_variant() { // <- choose variant A
/// Either::A( /// Either::A(
/// httpcodes::HttpBadRequest.with_body("Bad data")) /// HttpResponse::BadRequest().body("Bad data"))
/// } else { /// } else {
/// Either::B( // <- variant B /// Either::B( // <- variant B
/// result(HttpResponse::Ok() /// result(Ok(HttpResponse::Ok()
/// .content_type("text/html") /// .content_type("text/html")
/// .body(format!("Hello!")) /// .body("Hello!")))
/// .map_err(|e| e.into())).responder()) /// .responder())
/// } /// }
/// } /// }
/// # fn is_a_variant() -> bool { true } /// # fn is_a_variant() -> bool { true }
@ -105,8 +104,9 @@ impl<A, B> Responder for Either<A, B>
/// # extern crate actix_web; /// # extern crate actix_web;
/// # extern crate futures; /// # extern crate futures;
/// # #[macro_use] extern crate serde_derive; /// # #[macro_use] extern crate serde_derive;
/// use actix_web::*;
/// use futures::future::Future; /// use futures::future::Future;
/// use actix_web::{
/// Application, HttpRequest, HttpResponse, HttpMessage, Error, AsyncResponder};
/// ///
/// #[derive(Deserialize, Debug)] /// #[derive(Deserialize, Debug)]
/// struct MyObj { /// struct MyObj {
@ -117,7 +117,7 @@ impl<A, B> Responder for Either<A, B>
/// req.json() // <- get JsonBody future /// req.json() // <- get JsonBody future
/// .from_err() /// .from_err()
/// .and_then(|val: MyObj| { // <- deserialized value /// .and_then(|val: MyObj| { // <- deserialized value
/// Ok(httpcodes::HttpOk.into()) /// Ok(HttpResponse::Ok().into())
/// }) /// })
/// // Construct boxed future by using `AsyncResponder::responder()` method /// // Construct boxed future by using `AsyncResponder::responder()` method
/// .responder() /// .responder()

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -28,18 +28,18 @@ header! {
/// # Examples /// # Examples
/// ///
/// ```rust /// ```rust
/// use actix_web::httpcodes; /// use actix_web::HttpResponse;
/// use actix_web::http::header::{ETag, EntityTag}; /// 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()))); /// builder.set(ETag(EntityTag::new(false, "xyzzy".to_owned())));
/// ``` /// ```
/// ///
/// ```rust /// ```rust
/// use actix_web::httpcodes; /// use actix_web::HttpResponse;
/// use actix_web::http::header::{ETag, EntityTag}; /// 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()))); /// builder.set(ETag(EntityTag::new(true, "xyzzy".to_owned())));
/// ``` /// ```
(ETag, ETAG) => [EntityTag] (ETag, ETAG) => [EntityTag]

View File

@ -22,11 +22,11 @@ header! {
/// # Example /// # Example
/// ///
/// ```rust /// ```rust
/// use actix_web::httpcodes; /// use actix_web::HttpResponse;
/// use actix_web::http::header::Expires; /// use actix_web::http::header::Expires;
/// use std::time::{SystemTime, Duration}; /// 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); /// let expiration = SystemTime::now() + Duration::from_secs(60 * 60 * 24);
/// builder.set(Expires(expiration.into())); /// builder.set(Expires(expiration.into()));
/// ``` /// ```

View File

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

View File

@ -22,11 +22,11 @@ header! {
/// # Example /// # Example
/// ///
/// ```rust /// ```rust
/// use actix_web::httpcodes; /// use actix_web::HttpResponse;
/// use actix_web::http::header::IfModifiedSince; /// use actix_web::http::header::IfModifiedSince;
/// use std::time::{SystemTime, Duration}; /// 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); /// let modified = SystemTime::now() - Duration::from_secs(60 * 60 * 24);
/// builder.set(IfModifiedSince(modified.into())); /// builder.set(IfModifiedSince(modified.into()));
/// ``` /// ```

View File

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

View File

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

View File

@ -23,11 +23,11 @@ header! {
/// # Example /// # Example
/// ///
/// ```rust /// ```rust
/// use actix_web::httpcodes; /// use actix_web::HttpResponse;
/// use actix_web::http::header::IfUnmodifiedSince; /// use actix_web::http::header::IfUnmodifiedSince;
/// use std::time::{SystemTime, Duration}; /// 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); /// let modified = SystemTime::now() - Duration::from_secs(60 * 60 * 24);
/// builder.set(IfUnmodifiedSince(modified.into())); /// builder.set(IfUnmodifiedSince(modified.into()));
/// ``` /// ```

View File

@ -22,11 +22,11 @@ header! {
/// # Example /// # Example
/// ///
/// ```rust /// ```rust
/// use actix_web::httpcodes; /// use actix_web::HttpResponse;
/// use actix_web::http::header::LastModified; /// use actix_web::http::header::LastModified;
/// use std::time::{SystemTime, Duration}; /// 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); /// let modified = SystemTime::now() - Duration::from_secs(60 * 60 * 24);
/// builder.set(LastModified(modified.into())); /// builder.set(LastModified(modified.into()));
/// ``` /// ```

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -22,7 +22,7 @@
//! //!
//! ``` //! ```
//! # extern crate actix_web; //! # extern crate actix_web;
//! use actix_web::{Application, HttpRequest, http, httpcodes}; //! use actix_web::{http, Application, HttpRequest, HttpResponse};
//! use actix_web::middleware::csrf; //! use actix_web::middleware::csrf;
//! //!
//! fn handle_post(_: HttpRequest) -> &'static str { //! fn handle_post(_: HttpRequest) -> &'static str {
@ -36,7 +36,7 @@
//! .allowed_origin("https://www.example.com") //! .allowed_origin("https://www.example.com")
//! .finish()) //! .finish())
//! .resource("/", |r| { //! .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); //! r.method(http::Method::POST).f(handle_post);
//! }) //! })
//! .finish(); //! .finish();
@ -51,10 +51,9 @@ use std::collections::HashSet;
use bytes::Bytes; use bytes::Bytes;
use error::{Result, ResponseError}; use error::{Result, ResponseError};
use http::{HeaderMap, HttpTryFrom, Uri, header}; use http::{HeaderMap, HttpTryFrom, Uri, header};
use httpmessage::HttpMessage;
use httprequest::HttpRequest; use httprequest::HttpRequest;
use httpresponse::HttpResponse; use httpresponse::HttpResponse;
use httpmessage::HttpMessage;
use httpcodes::HttpForbidden;
use middleware::{Middleware, Started}; use middleware::{Middleware, Started};
/// Potential cross-site request forgery detected. /// Potential cross-site request forgery detected.
@ -73,7 +72,7 @@ pub enum CsrfError {
impl ResponseError for CsrfError { impl ResponseError for CsrfError {
fn error_response(&self) -> HttpResponse { 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 /// ```rust
/// # extern crate actix_web; /// # extern crate actix_web;
/// use actix_web::{Application, http, httpcodes, middleware}; /// use actix_web::{http, middleware, Application, HttpResponse};
/// ///
/// fn main() { /// fn main() {
/// let app = Application::new() /// let app = Application::new()
@ -22,8 +22,8 @@ use middleware::{Response, Middleware};
/// .header("X-Version", "0.2") /// .header("X-Version", "0.2")
/// .finish()) /// .finish())
/// .resource("/test", |r| { /// .resource("/test", |r| {
/// r.method(http::Method::GET).f(|_| httpcodes::HttpOk); /// r.method(http::Method::GET).f(|_| HttpResponse::Ok());
/// r.method(http::Method::HEAD).f(|_| httpcodes::HttpMethodNotAllowed); /// r.method(http::Method::HEAD).f(|_| HttpResponse::MethodNotAllowed());
/// }) /// })
/// .finish(); /// .finish();
/// } /// }
@ -112,14 +112,14 @@ mod tests {
let mut req = HttpRequest::default(); let mut req = HttpRequest::default();
let resp = HttpResponse::Ok().finish().unwrap(); let resp = HttpResponse::Ok().finish();
let resp = match mw.response(&mut req, resp) { let resp = match mw.response(&mut req, resp) {
Ok(Response::Done(resp)) => resp, Ok(Response::Done(resp)) => resp,
_ => panic!(), _ => panic!(),
}; };
assert_eq!(resp.headers().get(CONTENT_TYPE).unwrap(), "0001"); 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) { let resp = match mw.response(&mut req, resp) {
Ok(Response::Done(resp)) => resp, Ok(Response::Done(resp)) => resp,
_ => panic!(), _ => panic!(),

View File

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

View File

@ -20,16 +20,13 @@ pub trait Predicate<S> {
/// ///
/// ```rust /// ```rust
/// # extern crate actix_web; /// # extern crate actix_web;
/// # extern crate http; /// use actix_web::{pred, Application, HttpResponse};
/// # use actix_web::*;
/// # use actix_web::httpcodes::*;
/// use actix_web::pred;
/// ///
/// fn main() { /// fn main() {
/// Application::new() /// Application::new()
/// .resource("/index.html", |r| r.route() /// .resource("/index.html", |r| r.route()
/// .filter(pred::Any(pred::Get()).or(pred::Post())) /// .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> 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 /// ```rust
/// # extern crate actix_web; /// # extern crate actix_web;
/// # extern crate http; /// use actix_web::{pred, Application, HttpResponse};
/// # use actix_web::*;
/// # use actix_web::httpcodes::*;
/// use actix_web::pred;
/// ///
/// fn main() { /// fn main() {
/// Application::new() /// Application::new()
/// .resource("/index.html", |r| r.route() /// .resource("/index.html", |r| r.route()
/// .filter(pred::All(pred::Get()) /// .filter(pred::All(pred::Get())
/// .and(pred::Header("content-type", "plain/text"))) /// .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> { 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 http::{Method, StatusCode};
use pred; use pred;
use body::Body;
use route::Route; use route::Route;
use handler::{Reply, Handler, Responder, FromRequest}; use handler::{Reply, Handler, Responder, FromRequest};
use middleware::Middleware; use middleware::Middleware;
@ -172,7 +171,7 @@ impl<S: 'static> Resource<S> {
if let Some(resource) = default { if let Some(resource) = default {
resource.handle(req, None) resource.handle(req, None)
} else { } 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 error::Error;
use pred::Predicate; use pred::Predicate;
use http::StatusCode;
use handler::{Reply, ReplyItem, Handler, FromRequest, use handler::{Reply, ReplyItem, Handler, FromRequest,
Responder, RouteHandler, AsyncHandler, WrapHandler}; Responder, RouteHandler, AsyncHandler, WrapHandler};
use middleware::{Middleware, Response as MiddlewareResponse, Started as MiddlewareStarted}; use middleware::{Middleware, Response as MiddlewareResponse, Started as MiddlewareStarted};
use httpcodes::HttpNotFound;
use httprequest::HttpRequest; use httprequest::HttpRequest;
use httpresponse::HttpResponse; use httpresponse::HttpResponse;
use with::{with, with2, with3, WithHandler}; use with::{with, with2, with3, WithHandler};
@ -27,7 +27,7 @@ impl<S: 'static> Default for Route<S> {
fn default() -> Route<S> { fn default() -> Route<S> {
Route { Route {
preds: Vec::new(), 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 /// ```rust
/// # extern crate actix_web; /// # extern crate actix_web;
/// # use actix_web::*; /// # use actix_web::*;
/// # use actix_web::httpcodes::*;
/// # fn main() { /// # fn main() {
/// Application::new() /// Application::new()
/// .resource("/path", |r| /// .resource("/path", |r|
/// r.route() /// r.route()
/// .filter(pred::Get()) /// .filter(pred::Get())
/// .filter(pred::Header("content-type", "text/plain")) /// .filter(pred::Header("content-type", "text/plain"))
/// .f(|req| HttpOk) /// .f(|req| HttpResponse::Ok())
/// ) /// )
/// # .finish(); /// # .finish();
/// # } /// # }

View File

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

View File

@ -18,9 +18,9 @@ use tokio_core::reactor::Timeout;
use pipeline::Pipeline; use pipeline::Pipeline;
use error::PayloadError; use error::PayloadError;
use httpcodes::HttpNotFound;
use httpmessage::HttpMessage; use httpmessage::HttpMessage;
use httprequest::HttpRequest; use httprequest::HttpRequest;
use httpresponse::HttpResponse;
use payload::{Payload, PayloadWriter, PayloadStatus}; use payload::{Payload, PayloadWriter, PayloadStatus};
use super::h2writer::H2Writer; 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, payload: psender,
stream: H2Writer::new( stream: H2Writer::new(
resp, settings.get_shared_bytes(), Rc::clone(settings)), 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; pub(crate) const MAX_WRITE_BUFFER_SIZE: usize = 65_536;
/// Create new http server with application factory /// 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> pub fn new<F, U, H>(factory: F) -> HttpServer<H>
where F: Fn() -> U + Sync + Send + 'static, where F: Fn() -> U + Sync + Send + 'static,
U: IntoIterator<Item=H> + 'static, U: IntoIterator<Item=H> + 'static,

View File

@ -269,7 +269,7 @@ impl<H: IntoHttpHandler> HttpServer<H>
/// ///
/// HttpServer::new( /// HttpServer::new(
/// || Application::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") /// .bind("127.0.0.1:0").expect("Can not bind to 127.0.0.1:0")
/// .start(); /// .start();
/// # actix::Arbiter::system().do_send(actix::msgs::SystemExit(0)); /// # actix::Arbiter::system().do_send(actix::msgs::SystemExit(0));
@ -327,7 +327,7 @@ impl<H: IntoHttpHandler> HttpServer<H>
/// fn main() { /// fn main() {
/// HttpServer::new( /// HttpServer::new(
/// || Application::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") /// .bind("127.0.0.1:0").expect("Can not bind to 127.0.0.1:0")
/// .run(); /// .run();
/// } /// }

View File

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

View File

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

View File

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

View File

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