1
0
mirror of https://github.com/actix/actix-extras.git synced 2024-11-30 18:34:36 +01:00

rename httpcodes

This commit is contained in:
Nikolay Kim 2018-03-01 19:12:59 -08:00
parent 4e13505b92
commit 206c4e581a
29 changed files with 219 additions and 110 deletions

View File

@ -4,6 +4,8 @@
* Rename `Route::p()` to `Route::filter()` * Rename `Route::p()` to `Route::filter()`
* Better naming for http codes
* Fix payload parse in situation when socket data is not ready. * Fix payload parse in situation when socket data is not ready.
* Fix Session mutable borrow lifetime #87 * Fix Session mutable borrow lifetime #87

View File

@ -53,7 +53,7 @@ impl<S> Middleware<S> for Headers {
fn main() { fn main() {
Application::new() Application::new()
.middleware(Headers) // <- Register middleware, this method could be called multiple times .middleware(Headers) // <- Register middleware, this method could be called multiple times
.resource("/", |r| r.h(httpcodes::HTTPOk)); .resource("/", |r| r.h(httpcodes::HttpOk));
} }
``` ```
@ -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(Method::GET).f(|req| httpcodes::HTTPOk); r.method(Method::GET).f(|req| httpcodes::HttpOk);
r.method(Method::HEAD).f(|req| httpcodes::HTTPMethodNotAllowed); r.method(Method::HEAD).f(|req| httpcodes::HttpMethodNotAllowed);
}) })
.finish(); .finish();
} }

View File

@ -110,8 +110,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(httpcodes::HttpOk.build().json(user)?),
Err(_) => Ok(httpcodes::HTTPInternalServerError.into()) Err(_) => Ok(httpcodes::HttpInternalServerError.into())
} }
}) })
.responder() .responder()

View File

@ -49,12 +49,12 @@ 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| httpcodes::HttpOk)),
Application::new() Application::new()
.prefix("/app2") .prefix("/app2")
.resource("/", |r| r.f(|r| httpcodes::HTTPOk)), .resource("/", |r| r.f(|r| httpcodes::HttpOk)),
Application::new() Application::new()
.resource("/", |r| r.f(|r| httpcodes::HTTPOk)), .resource("/", |r| r.f(|r| httpcodes::HttpOk)),
]); ]);
} }
``` ```

View File

@ -20,7 +20,7 @@ fn main() {
HttpServer::new( HttpServer::new(
|| Application::new() || Application::new()
.resource("/", |r| r.h(httpcodes::HTTPOk))) .resource("/", |r| r.h(httpcodes::HttpOk)))
.bind("127.0.0.1:59080").unwrap() .bind("127.0.0.1:59080").unwrap()
.start(); .start();
@ -57,7 +57,7 @@ fn main() {
let sys = actix::System::new("http-server"); let sys = actix::System::new("http-server");
let addr = HttpServer::new( let addr = HttpServer::new(
|| Application::new() || Application::new()
.resource("/", |r| r.h(httpcodes::HTTPOk))) .resource("/", |r| r.h(httpcodes::HttpOk)))
.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();
@ -85,7 +85,7 @@ use actix_web::*;
fn main() { fn main() {
HttpServer::new( HttpServer::new(
|| Application::new() || Application::new()
.resource("/", |r| r.h(httpcodes::HTTPOk))) .resource("/", |r| r.h(httpcodes::HttpOk)))
.threads(4); // <- Start 4 workers .threads(4); // <- Start 4 workers
} }
``` ```
@ -146,7 +146,7 @@ use actix_web::*;
fn main() { fn main() {
HttpServer::new(|| HttpServer::new(||
Application::new() Application::new()
.resource("/", |r| r.h(httpcodes::HTTPOk))) .resource("/", |r| r.h(httpcodes::HttpOk)))
.keep_alive(None); // <- Use `SO_KEEPALIVE` socket option. .keep_alive(None); // <- Use `SO_KEEPALIVE` socket option.
} }
``` ```
@ -155,7 +155,7 @@ If first option is selected then *keep alive* state
calculated based on response's *connection-type*. By default calculated based on response's *connection-type*. By default
`HttpResponse::connection_type` is not defined in that case *keep alive* `HttpResponse::connection_type` is not defined in that case *keep alive*
defined by request's http version. Keep alive is off for *HTTP/1.0* defined by request's http version. Keep alive is off for *HTTP/1.0*
and is on for *HTTP/1.1* and "HTTP/2.0". and is on for *HTTP/1.1* and *HTTP/2.0*.
*Connection type* could be change with `HttpResponseBuilder::connection_type()` method. *Connection type* could be change with `HttpResponseBuilder::connection_type()` method.
@ -165,7 +165,7 @@ and is on for *HTTP/1.1* and "HTTP/2.0".
use actix_web::*; use actix_web::*;
fn index(req: HttpRequest) -> HttpResponse { fn index(req: HttpRequest) -> HttpResponse {
HTTPOk.build() HttpOk.build()
.connection_type(headers::ConnectionType::Close) // <- Close connection .connection_type(headers::ConnectionType::Close) // <- Close connection
.force_close() // <- Alternative method .force_close() // <- Alternative method
.finish().unwrap() .finish().unwrap()

View File

@ -65,7 +65,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() httpcodes::HttpOk.into()
} }
} }
# fn main() {} # fn main() {}
@ -90,7 +90,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() httpcodes::HttpOk.into()
} }
} }

View File

@ -14,7 +14,7 @@ impl<T: Responder, E: Into<Error>> Responder for Result<T, E>
And any error that implements `ResponseError` can be converted into `Error` object. And any error that implements `ResponseError` can be converted into `Error` object.
For example if *handler* function returns `io::Error`, it would be converted For example if *handler* function returns `io::Error`, it would be converted
into `HTTPInternalServerError` response. Implementation for `io::Error` is provided into `HttpInternalServerError` response. Implementation for `io::Error` is provided
by default. by default.
```rust ```rust

View File

@ -32,7 +32,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| HttpOk))
.finish(); .finish();
} }
``` ```
@ -52,7 +52,7 @@ returns *NOT FOUND* http resources.
Resource contains set of routes. Each route in turn has set of predicates and handler. Resource contains set of routes. Each route in turn has set of predicates and handler.
New route could be created with `Resource::route()` method which returns reference New route could be created with `Resource::route()` method which returns reference
to new *Route* instance. By default *route* does not contain any predicates, so matches to new *Route* instance. By default *route* does not contain any predicates, so matches
all requests and default handler is `HTTPNotFound`. all requests and default handler is `HttpNotFound`.
Application routes incoming requests based on route criteria which is defined during Application routes incoming requests based on route criteria which is defined during
resource registration and route registration. Resource matches all routes it contains in resource registration and route registration. Resource matches all routes it contains in
@ -70,7 +70,7 @@ 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| HttpOk)
) )
.finish(); .finish();
} }
@ -336,14 +336,14 @@ resource with the name "foo" and the pattern "{a}/{b}/{c}", you might do this.
# #
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() HttpOk.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(|_| httpcodes::HTTPOk); r.method(Method::GET).f(|_| httpcodes::HttpOk);
}) })
.finish(); .finish();
} }
@ -367,7 +367,7 @@ use actix_web::*;
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(httpcodes::HttpOk.into())
} }
fn main() { fn main() {
@ -404,7 +404,7 @@ This handler designed to be use as a handler for application's *default resource
# use actix_web::*; # use actix_web::*;
# #
# fn index(req: HttpRequest) -> httpcodes::StaticResponse { # fn index(req: HttpRequest) -> httpcodes::StaticResponse {
# httpcodes::HTTPOk # httpcodes::HttpOk
# } # }
fn main() { fn main() {
let app = Application::new() let app = Application::new()
@ -429,7 +429,7 @@ It is possible to register path normalization only for *GET* requests only
# use actix_web::*; # use actix_web::*;
# #
# fn index(req: HttpRequest) -> httpcodes::StaticResponse { # fn index(req: HttpRequest) -> httpcodes::StaticResponse {
# httpcodes::HTTPOk # httpcodes::HttpOk
# } # }
fn main() { fn main() {
let app = Application::new() let app = Application::new()
@ -503,7 +503,7 @@ fn main() {
.resource("/index.html", |r| .resource("/index.html", |r|
r.route() r.route()
.filter(ContentTypeHeader) .filter(ContentTypeHeader)
.h(HTTPOk)); .h(HttpOk));
} }
``` ```
@ -531,7 +531,7 @@ fn main() {
.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| HttpMethodNotAllowed))
.finish(); .finish();
} }
``` ```
@ -567,8 +567,8 @@ use actix_web::httpcodes::*;
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| HttpNotFound);
r.route().filter(pred::Not(pred::Get())).f(|req| HTTPMethodNotAllowed); r.route().filter(pred::Not(pred::Get())).f(|req| HttpMethodNotAllowed);
}) })
# .finish(); # .finish();
} }

View File

@ -84,7 +84,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(httpcodes::HttpOk.build().json(val)?) // <- send response
}) })
.responder() .responder()
} }
@ -117,7 +117,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(httpcodes::HttpOk.build().json(obj)?) // <- send response
}) })
.responder() .responder()
} }
@ -251,7 +251,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(httpcodes::HttpOk.into())
}) })
.responder() .responder()
} }

View File

@ -20,10 +20,10 @@ 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(header::CONTENT_TYPE) {
if let Ok(s) = hdr.to_str() { if let Ok(s) = hdr.to_str() {
return httpcodes::HTTPOk.into() return httpcodes::HttpOk.into()
} }
} }
httpcodes::HTTPBadRequest.into() httpcodes::HttpBadRequest.into()
} }
fn main() { fn main() {
@ -59,7 +59,7 @@ use actix_web::*;
use actix_web::test::TestServer; use actix_web::test::TestServer;
fn index(req: HttpRequest) -> HttpResponse { fn index(req: HttpRequest) -> HttpResponse {
httpcodes::HTTPOk.into() httpcodes::HttpOk.into()
} }
fn main() { fn main() {
@ -84,7 +84,7 @@ use actix_web::*;
use actix_web::test::TestServer; use actix_web::test::TestServer;
fn index(req: HttpRequest) -> HttpResponse { fn index(req: HttpRequest) -> HttpResponse {
httpcodes::HTTPOk.into() httpcodes::HttpOk.into()
} }
/// This function get called by http server. /// This function get called by http server.

View File

@ -183,8 +183,8 @@ impl<S> Application<S> where S: 'static {
/// let app = Application::new() /// let app = Application::new()
/// .prefix("/app") /// .prefix("/app")
/// .resource("/test", |r| { /// .resource("/test", |r| {
/// r.method(Method::GET).f(|_| httpcodes::HTTPOk); /// r.method(Method::GET).f(|_| httpcodes::HttpOk);
/// r.method(Method::HEAD).f(|_| httpcodes::HTTPMethodNotAllowed); /// r.method(Method::HEAD).f(|_| httpcodes::HttpMethodNotAllowed);
/// }) /// })
/// .finish(); /// .finish();
/// } /// }
@ -226,8 +226,8 @@ impl<S> Application<S> where S: 'static {
/// fn main() { /// fn main() {
/// let app = Application::new() /// let app = Application::new()
/// .resource("/test", |r| { /// .resource("/test", |r| {
/// r.method(Method::GET).f(|_| httpcodes::HTTPOk); /// r.method(Method::GET).f(|_| httpcodes::HttpOk);
/// r.method(Method::HEAD).f(|_| httpcodes::HTTPMethodNotAllowed); /// r.method(Method::HEAD).f(|_| httpcodes::HttpMethodNotAllowed);
/// }); /// });
/// } /// }
/// ``` /// ```
@ -281,7 +281,7 @@ impl<S> Application<S> where S: 'static {
/// 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(httpcodes::HttpOk.into())
/// } /// }
/// ///
/// fn main() { /// fn main() {
@ -320,9 +320,9 @@ impl<S> Application<S> where S: 'static {
/// let app = Application::new() /// let app = Application::new()
/// .handler("/app", |req: HttpRequest| { /// .handler("/app", |req: HttpRequest| {
/// match *req.method() { /// match *req.method() {
/// Method::GET => httpcodes::HTTPOk, /// Method::GET => httpcodes::HttpOk,
/// Method::POST => httpcodes::HTTPMethodNotAllowed, /// Method::POST => httpcodes::HttpMethodNotAllowed,
/// _ => httpcodes::HTTPNotFound, /// _ => httpcodes::HttpNotFound,
/// }}); /// }});
/// } /// }
/// ``` /// ```
@ -394,11 +394,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.h(httpcodes::HttpOk))
/// .boxed(), /// .boxed(),
/// Application::with_state(State2) /// Application::with_state(State2)
/// .prefix("/app2") /// .prefix("/app2")
/// .resource("/", |r| r.h(httpcodes::HTTPOk)) /// .resource("/", |r| r.h(httpcodes::HttpOk))
/// .boxed() ]}) /// .boxed() ]})
/// .bind("127.0.0.1:8080").unwrap() /// .bind("127.0.0.1:8080").unwrap()
/// .run() /// .run()
@ -459,7 +459,7 @@ mod tests {
#[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.h(httpcodes::HttpOk))
.finish(); .finish();
let req = TestRequest::with_uri("/test").finish(); let req = TestRequest::with_uri("/test").finish();
@ -471,7 +471,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.h(httpcodes::HttpMethodNotAllowed))
.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);
@ -482,7 +482,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.h(httpcodes::HttpOk))
.finish(); .finish();
assert!(app.handle(HttpRequest::default()).is_err()); assert!(app.handle(HttpRequest::default()).is_err());
} }
@ -490,7 +490,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.h(httpcodes::HttpOk))
.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);
@ -501,7 +501,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.h(httpcodes::HttpOk))
.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);
@ -523,7 +523,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", httpcodes::HttpOk)
.finish(); .finish();
let req = TestRequest::with_uri("/test").finish(); let req = TestRequest::with_uri("/test").finish();
@ -551,7 +551,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", httpcodes::HttpOk)
.finish(); .finish();
let req = TestRequest::with_uri("/test").finish(); let req = TestRequest::with_uri("/test").finish();

View File

@ -24,7 +24,7 @@ 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}; 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
@ -336,7 +336,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") HttpExpectationFailed.with_body("Unknown Expect")
} }
} }
@ -386,9 +386,9 @@ 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 => httpcodes::HttpPayloadTooLarge.into(),
UrlencodedError::UnknownLength => httpcodes::HTTPLengthRequired.into(), UrlencodedError::UnknownLength => httpcodes::HttpLengthRequired.into(),
_ => httpcodes::HTTPBadRequest.into(), _ => httpcodes::HttpBadRequest.into(),
} }
} }
} }
@ -421,8 +421,8 @@ 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::HttpPayloadTooLarge.into(),
_ => httpcodes::HTTPBadRequest.into(), _ => httpcodes::HttpBadRequest.into(),
} }
} }
} }

View File

@ -15,7 +15,7 @@ use handler::{Handler, Responder};
use headers::ContentEncoding; use headers::ContentEncoding;
use httprequest::HttpRequest; use httprequest::HttpRequest;
use httpresponse::HttpResponse; use httpresponse::HttpResponse;
use httpcodes::{HTTPOk, HTTPFound}; use httpcodes::{HttpOk, HttpFound};
/// 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.
@ -84,7 +84,7 @@ impl Responder for NamedFile {
type Error = io::Error; type Error = io::Error;
fn respond_to(mut self, _: HttpRequest) -> Result<HttpResponse, io::Error> { fn respond_to(mut self, _: HttpRequest) -> Result<HttpResponse, io::Error> {
let mut resp = HTTPOk.build(); let mut resp = HttpOk.build();
resp.content_encoding(ContentEncoding::Identity); resp.content_encoding(ContentEncoding::Identity);
if let Some(ext) = self.path().extension() { if let Some(ext) = self.path().extension() {
let mime = get_mime_type(&ext.to_string_lossy()); let mime = get_mime_type(&ext.to_string_lossy());
@ -164,7 +164,7 @@ 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(HttpOk.build()
.content_type("text/html; charset=utf-8") .content_type("text/html; charset=utf-8")
.body(html).unwrap()) .body(html).unwrap())
} }
@ -289,7 +289,7 @@ impl<S> Handler<S> for StaticFiles {
} }
new_path.push_str(redir_index); new_path.push_str(redir_index);
Ok(FilesystemElement::Redirect( Ok(FilesystemElement::Redirect(
HTTPFound HttpFound
.build() .build()
.header::<_, &str>("LOCATION", &new_path) .header::<_, &str>("LOCATION", &new_path)
.finish().unwrap())) .finish().unwrap()))

View File

@ -309,7 +309,7 @@ impl<S, H, F, R, E> RouteHandler<S> for AsyncHandler<S, H, F, R, E>
/// # use actix_web::*; /// # use actix_web::*;
/// # /// #
/// # fn index(req: HttpRequest) -> httpcodes::StaticResponse { /// # fn index(req: HttpRequest) -> httpcodes::StaticResponse {
/// # httpcodes::HTTPOk /// # httpcodes::HttpOk
/// # } /// # }
/// fn main() { /// fn main() {
/// let app = Application::new() /// let app = Application::new()

View File

@ -7,67 +7,174 @@ use handler::{Reply, Handler, RouteHandler, Responder};
use httprequest::HttpRequest; use httprequest::HttpRequest;
use httpresponse::{HttpResponse, HttpResponseBuilder}; use httpresponse::{HttpResponse, HttpResponseBuilder};
pub const HttpOk: StaticResponse = StaticResponse(StatusCode::OK);
pub const HttpCreated: StaticResponse = StaticResponse(StatusCode::CREATED);
pub const HttpAccepted: StaticResponse = StaticResponse(StatusCode::ACCEPTED);
pub const HttpNonAuthoritativeInformation: StaticResponse =
StaticResponse(StatusCode::NON_AUTHORITATIVE_INFORMATION);
pub const HttpNoContent: StaticResponse = StaticResponse(StatusCode::NO_CONTENT);
pub const HttpResetContent: StaticResponse = StaticResponse(StatusCode::RESET_CONTENT);
pub const HttpPartialContent: StaticResponse = StaticResponse(StatusCode::PARTIAL_CONTENT);
pub const HttpMultiStatus: StaticResponse = StaticResponse(StatusCode::MULTI_STATUS);
pub const HttpAlreadyReported: StaticResponse = StaticResponse(StatusCode::ALREADY_REPORTED);
pub const HttpMultipleChoices: StaticResponse = StaticResponse(StatusCode::MULTIPLE_CHOICES);
pub const HttpMovedPermanenty: StaticResponse = StaticResponse(StatusCode::MOVED_PERMANENTLY);
pub const HttpFound: StaticResponse = StaticResponse(StatusCode::FOUND);
pub const HttpSeeOther: StaticResponse = StaticResponse(StatusCode::SEE_OTHER);
pub const HttpNotModified: StaticResponse = StaticResponse(StatusCode::NOT_MODIFIED);
pub const HttpUseProxy: StaticResponse = StaticResponse(StatusCode::USE_PROXY);
pub const HttpTemporaryRedirect: StaticResponse =
StaticResponse(StatusCode::TEMPORARY_REDIRECT);
pub const HttpPermanentRedirect: StaticResponse =
StaticResponse(StatusCode::PERMANENT_REDIRECT);
pub const HttpBadRequest: StaticResponse = StaticResponse(StatusCode::BAD_REQUEST);
pub const HttpUnauthorized: StaticResponse = StaticResponse(StatusCode::UNAUTHORIZED);
pub const HttpPaymentRequired: StaticResponse = StaticResponse(StatusCode::PAYMENT_REQUIRED);
pub const HttpForbidden: StaticResponse = StaticResponse(StatusCode::FORBIDDEN);
pub const HttpNotFound: StaticResponse = StaticResponse(StatusCode::NOT_FOUND);
pub const HttpMethodNotAllowed: StaticResponse =
StaticResponse(StatusCode::METHOD_NOT_ALLOWED);
pub const HttpNotAcceptable: StaticResponse = StaticResponse(StatusCode::NOT_ACCEPTABLE);
pub const HttpProxyAuthenticationRequired: StaticResponse =
StaticResponse(StatusCode::PROXY_AUTHENTICATION_REQUIRED);
pub const HttpRequestTimeout: StaticResponse = StaticResponse(StatusCode::REQUEST_TIMEOUT);
pub const HttpConflict: StaticResponse = StaticResponse(StatusCode::CONFLICT);
pub const HttpGone: StaticResponse = StaticResponse(StatusCode::GONE);
pub const HttpLengthRequired: StaticResponse = StaticResponse(StatusCode::LENGTH_REQUIRED);
pub const HttpPreconditionFailed: StaticResponse =
StaticResponse(StatusCode::PRECONDITION_FAILED);
pub const HttpPayloadTooLarge: StaticResponse = StaticResponse(StatusCode::PAYLOAD_TOO_LARGE);
pub const HttpUriTooLong: StaticResponse = StaticResponse(StatusCode::URI_TOO_LONG);
pub const HttpUnsupportedMediaType: StaticResponse =
StaticResponse(StatusCode::UNSUPPORTED_MEDIA_TYPE);
pub const HttpRangeNotSatisfiable: StaticResponse =
StaticResponse(StatusCode::RANGE_NOT_SATISFIABLE);
pub const HttpExpectationFailed: StaticResponse =
StaticResponse(StatusCode::EXPECTATION_FAILED);
pub const HttpInternalServerError: StaticResponse =
StaticResponse(StatusCode::INTERNAL_SERVER_ERROR);
pub const HttpNotImplemented: StaticResponse = StaticResponse(StatusCode::NOT_IMPLEMENTED);
pub const HttpBadGateway: StaticResponse = StaticResponse(StatusCode::BAD_GATEWAY);
pub const HttpServiceUnavailable: StaticResponse =
StaticResponse(StatusCode::SERVICE_UNAVAILABLE);
pub const HttpGatewayTimeout: StaticResponse =
StaticResponse(StatusCode::GATEWAY_TIMEOUT);
pub const HttpVersionNotSupported: StaticResponse =
StaticResponse(StatusCode::HTTP_VERSION_NOT_SUPPORTED);
pub const HttpVariantAlsoNegotiates: StaticResponse =
StaticResponse(StatusCode::VARIANT_ALSO_NEGOTIATES);
pub const HttpInsufficientStorage: StaticResponse =
StaticResponse(StatusCode::INSUFFICIENT_STORAGE);
pub const HttpLoopDetected: StaticResponse = StaticResponse(StatusCode::LOOP_DETECTED);
#[doc(hidden)]
pub const HTTPOk: StaticResponse = StaticResponse(StatusCode::OK); pub const HTTPOk: StaticResponse = StaticResponse(StatusCode::OK);
#[doc(hidden)]
pub const HTTPCreated: StaticResponse = StaticResponse(StatusCode::CREATED); pub const HTTPCreated: StaticResponse = StaticResponse(StatusCode::CREATED);
#[doc(hidden)]
pub const HTTPAccepted: StaticResponse = StaticResponse(StatusCode::ACCEPTED); pub const HTTPAccepted: StaticResponse = StaticResponse(StatusCode::ACCEPTED);
#[doc(hidden)]
pub const HTTPNonAuthoritativeInformation: StaticResponse = pub const HTTPNonAuthoritativeInformation: StaticResponse =
StaticResponse(StatusCode::NON_AUTHORITATIVE_INFORMATION); StaticResponse(StatusCode::NON_AUTHORITATIVE_INFORMATION);
#[doc(hidden)]
pub const HTTPNoContent: StaticResponse = StaticResponse(StatusCode::NO_CONTENT); pub const HTTPNoContent: StaticResponse = StaticResponse(StatusCode::NO_CONTENT);
#[doc(hidden)]
pub const HTTPResetContent: StaticResponse = StaticResponse(StatusCode::RESET_CONTENT); pub const HTTPResetContent: StaticResponse = StaticResponse(StatusCode::RESET_CONTENT);
#[doc(hidden)]
pub const HTTPPartialContent: StaticResponse = StaticResponse(StatusCode::PARTIAL_CONTENT); pub const HTTPPartialContent: StaticResponse = StaticResponse(StatusCode::PARTIAL_CONTENT);
#[doc(hidden)]
pub const HTTPMultiStatus: StaticResponse = StaticResponse(StatusCode::MULTI_STATUS); pub const HTTPMultiStatus: StaticResponse = StaticResponse(StatusCode::MULTI_STATUS);
#[doc(hidden)]
pub const HTTPAlreadyReported: StaticResponse = StaticResponse(StatusCode::ALREADY_REPORTED); pub const HTTPAlreadyReported: StaticResponse = StaticResponse(StatusCode::ALREADY_REPORTED);
#[doc(hidden)]
pub const HTTPMultipleChoices: StaticResponse = StaticResponse(StatusCode::MULTIPLE_CHOICES); pub const HTTPMultipleChoices: StaticResponse = StaticResponse(StatusCode::MULTIPLE_CHOICES);
#[doc(hidden)]
pub const HTTPMovedPermanenty: StaticResponse = StaticResponse(StatusCode::MOVED_PERMANENTLY); pub const HTTPMovedPermanenty: StaticResponse = StaticResponse(StatusCode::MOVED_PERMANENTLY);
#[doc(hidden)]
pub const HTTPFound: StaticResponse = StaticResponse(StatusCode::FOUND); pub const HTTPFound: StaticResponse = StaticResponse(StatusCode::FOUND);
#[doc(hidden)]
pub const HTTPSeeOther: StaticResponse = StaticResponse(StatusCode::SEE_OTHER); pub const HTTPSeeOther: StaticResponse = StaticResponse(StatusCode::SEE_OTHER);
#[doc(hidden)]
pub const HTTPNotModified: StaticResponse = StaticResponse(StatusCode::NOT_MODIFIED); pub const HTTPNotModified: StaticResponse = StaticResponse(StatusCode::NOT_MODIFIED);
#[doc(hidden)]
pub const HTTPUseProxy: StaticResponse = StaticResponse(StatusCode::USE_PROXY); pub const HTTPUseProxy: StaticResponse = StaticResponse(StatusCode::USE_PROXY);
#[doc(hidden)]
pub const HTTPTemporaryRedirect: StaticResponse = pub const HTTPTemporaryRedirect: StaticResponse =
StaticResponse(StatusCode::TEMPORARY_REDIRECT); StaticResponse(StatusCode::TEMPORARY_REDIRECT);
#[doc(hidden)]
pub const HTTPPermanentRedirect: StaticResponse = pub const HTTPPermanentRedirect: StaticResponse =
StaticResponse(StatusCode::PERMANENT_REDIRECT); StaticResponse(StatusCode::PERMANENT_REDIRECT);
#[doc(hidden)]
pub const HTTPBadRequest: StaticResponse = StaticResponse(StatusCode::BAD_REQUEST); pub const HTTPBadRequest: StaticResponse = StaticResponse(StatusCode::BAD_REQUEST);
#[doc(hidden)]
pub const HTTPUnauthorized: StaticResponse = StaticResponse(StatusCode::UNAUTHORIZED); pub const HTTPUnauthorized: StaticResponse = StaticResponse(StatusCode::UNAUTHORIZED);
#[doc(hidden)]
pub const HTTPPaymentRequired: StaticResponse = StaticResponse(StatusCode::PAYMENT_REQUIRED); pub const HTTPPaymentRequired: StaticResponse = StaticResponse(StatusCode::PAYMENT_REQUIRED);
#[doc(hidden)]
pub const HTTPForbidden: StaticResponse = StaticResponse(StatusCode::FORBIDDEN); pub const HTTPForbidden: StaticResponse = StaticResponse(StatusCode::FORBIDDEN);
#[doc(hidden)]
pub const HTTPNotFound: StaticResponse = StaticResponse(StatusCode::NOT_FOUND); pub const HTTPNotFound: StaticResponse = StaticResponse(StatusCode::NOT_FOUND);
#[doc(hidden)]
pub const HTTPMethodNotAllowed: StaticResponse = pub const HTTPMethodNotAllowed: StaticResponse =
StaticResponse(StatusCode::METHOD_NOT_ALLOWED); StaticResponse(StatusCode::METHOD_NOT_ALLOWED);
#[doc(hidden)]
pub const HTTPNotAcceptable: StaticResponse = StaticResponse(StatusCode::NOT_ACCEPTABLE); pub const HTTPNotAcceptable: StaticResponse = StaticResponse(StatusCode::NOT_ACCEPTABLE);
#[doc(hidden)]
pub const HTTPProxyAuthenticationRequired: StaticResponse = pub const HTTPProxyAuthenticationRequired: StaticResponse =
StaticResponse(StatusCode::PROXY_AUTHENTICATION_REQUIRED); StaticResponse(StatusCode::PROXY_AUTHENTICATION_REQUIRED);
#[doc(hidden)]
pub const HTTPRequestTimeout: StaticResponse = StaticResponse(StatusCode::REQUEST_TIMEOUT); pub const HTTPRequestTimeout: StaticResponse = StaticResponse(StatusCode::REQUEST_TIMEOUT);
#[doc(hidden)]
pub const HTTPConflict: StaticResponse = StaticResponse(StatusCode::CONFLICT); pub const HTTPConflict: StaticResponse = StaticResponse(StatusCode::CONFLICT);
#[doc(hidden)]
pub const HTTPGone: StaticResponse = StaticResponse(StatusCode::GONE); pub const HTTPGone: StaticResponse = StaticResponse(StatusCode::GONE);
#[doc(hidden)]
pub const HTTPLengthRequired: StaticResponse = StaticResponse(StatusCode::LENGTH_REQUIRED); pub const HTTPLengthRequired: StaticResponse = StaticResponse(StatusCode::LENGTH_REQUIRED);
#[doc(hidden)]
pub const HTTPPreconditionFailed: StaticResponse = pub const HTTPPreconditionFailed: StaticResponse =
StaticResponse(StatusCode::PRECONDITION_FAILED); StaticResponse(StatusCode::PRECONDITION_FAILED);
#[doc(hidden)]
pub const HTTPPayloadTooLarge: StaticResponse = StaticResponse(StatusCode::PAYLOAD_TOO_LARGE); pub const HTTPPayloadTooLarge: StaticResponse = StaticResponse(StatusCode::PAYLOAD_TOO_LARGE);
#[doc(hidden)]
pub const HTTPUriTooLong: StaticResponse = StaticResponse(StatusCode::URI_TOO_LONG); pub const HTTPUriTooLong: StaticResponse = StaticResponse(StatusCode::URI_TOO_LONG);
#[doc(hidden)]
pub const HTTPUnsupportedMediaType: StaticResponse = pub const HTTPUnsupportedMediaType: StaticResponse =
StaticResponse(StatusCode::UNSUPPORTED_MEDIA_TYPE); StaticResponse(StatusCode::UNSUPPORTED_MEDIA_TYPE);
#[doc(hidden)]
pub const HTTPRangeNotSatisfiable: StaticResponse = pub const HTTPRangeNotSatisfiable: StaticResponse =
StaticResponse(StatusCode::RANGE_NOT_SATISFIABLE); StaticResponse(StatusCode::RANGE_NOT_SATISFIABLE);
#[doc(hidden)]
pub const HTTPExpectationFailed: StaticResponse = pub const HTTPExpectationFailed: StaticResponse =
StaticResponse(StatusCode::EXPECTATION_FAILED); StaticResponse(StatusCode::EXPECTATION_FAILED);
#[doc(hidden)]
pub const HTTPInternalServerError: StaticResponse = pub const HTTPInternalServerError: StaticResponse =
StaticResponse(StatusCode::INTERNAL_SERVER_ERROR); StaticResponse(StatusCode::INTERNAL_SERVER_ERROR);
#[doc(hidden)]
pub const HTTPNotImplemented: StaticResponse = StaticResponse(StatusCode::NOT_IMPLEMENTED); pub const HTTPNotImplemented: StaticResponse = StaticResponse(StatusCode::NOT_IMPLEMENTED);
#[doc(hidden)]
pub const HTTPBadGateway: StaticResponse = StaticResponse(StatusCode::BAD_GATEWAY); pub const HTTPBadGateway: StaticResponse = StaticResponse(StatusCode::BAD_GATEWAY);
#[doc(hidden)]
pub const HTTPServiceUnavailable: StaticResponse = pub const HTTPServiceUnavailable: StaticResponse =
StaticResponse(StatusCode::SERVICE_UNAVAILABLE); StaticResponse(StatusCode::SERVICE_UNAVAILABLE);
#[doc(hidden)]
pub const HTTPGatewayTimeout: StaticResponse = pub const HTTPGatewayTimeout: StaticResponse =
StaticResponse(StatusCode::GATEWAY_TIMEOUT); StaticResponse(StatusCode::GATEWAY_TIMEOUT);
#[doc(hidden)]
pub const HTTPVersionNotSupported: StaticResponse = pub const HTTPVersionNotSupported: StaticResponse =
StaticResponse(StatusCode::HTTP_VERSION_NOT_SUPPORTED); StaticResponse(StatusCode::HTTP_VERSION_NOT_SUPPORTED);
#[doc(hidden)]
pub const HTTPVariantAlsoNegotiates: StaticResponse = pub const HTTPVariantAlsoNegotiates: StaticResponse =
StaticResponse(StatusCode::VARIANT_ALSO_NEGOTIATES); StaticResponse(StatusCode::VARIANT_ALSO_NEGOTIATES);
#[doc(hidden)]
pub const HTTPInsufficientStorage: StaticResponse = pub const HTTPInsufficientStorage: StaticResponse =
StaticResponse(StatusCode::INSUFFICIENT_STORAGE); StaticResponse(StatusCode::INSUFFICIENT_STORAGE);
#[doc(hidden)]
pub const HTTPLoopDetected: StaticResponse = StaticResponse(StatusCode::LOOP_DETECTED); pub const HTTPLoopDetected: StaticResponse = StaticResponse(StatusCode::LOOP_DETECTED);

View File

@ -114,7 +114,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(httpcodes::HttpOk.into())
/// }).responder() /// }).responder()
/// } /// }
/// # fn main() {} /// # fn main() {}
@ -148,7 +148,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(httpcodes::HttpOk.into())
/// }) /// })
/// .responder() /// .responder()
/// } /// }
@ -187,7 +187,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(httpcodes::HttpOk.into())
/// }).responder() /// }).responder()
/// } /// }
/// # fn main() {} /// # fn main() {}

View File

@ -249,14 +249,14 @@ impl<S> HttpRequest<S> {
/// # /// #
/// 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() /// HttpOk.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(Method::GET).f(|_| httpcodes::HTTPOk); /// r.method(Method::GET).f(|_| httpcodes::HttpOk);
/// }) /// })
/// .finish(); /// .finish();
/// } /// }

View File

@ -252,7 +252,7 @@ impl HttpResponseBuilder {
/// use http::header; /// use http::header;
/// ///
/// fn index(req: HttpRequest) -> Result<HttpResponse> { /// fn index(req: HttpRequest) -> Result<HttpResponse> {
/// Ok(HTTPOk.build() /// Ok(HttpOk.build()
/// .header("X-TEST", "value") /// .header("X-TEST", "value")
/// .header(header::CONTENT_TYPE, "application/json") /// .header(header::CONTENT_TYPE, "application/json")
/// .finish()?) /// .finish()?)
@ -372,7 +372,7 @@ impl HttpResponseBuilder {
/// use actix_web::headers::Cookie; /// use actix_web::headers::Cookie;
/// ///
/// fn index(req: HttpRequest) -> Result<HttpResponse> { /// fn index(req: HttpRequest) -> Result<HttpResponse> {
/// Ok(HTTPOk.build() /// Ok(HttpOk.build()
/// .cookie( /// .cookie(
/// Cookie::build("name", "value") /// Cookie::build("name", "value")
/// .domain("www.rust-lang.org") /// .domain("www.rust-lang.org")
@ -753,7 +753,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 = httpcodes::HttpOk
.build() .build()
.cookie(headers::Cookie::build("name", "value") .cookie(headers::Cookie::build("name", "value")
.domain("www.rust-lang.org") .domain("www.rust-lang.org")

View File

@ -75,7 +75,7 @@ impl<T: Serialize> Responder 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(httpcodes::HttpOk.into())
/// }).responder() /// }).responder()
/// } /// }
/// # fn main() {} /// # fn main() {}

View File

@ -38,8 +38,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(Method::GET).f(|_| httpcodes::HTTPOk); //! r.method(Method::GET).f(|_| httpcodes::HttpOk);
//! r.method(Method::HEAD).f(|_| httpcodes::HTTPMethodNotAllowed); //! r.method(Method::HEAD).f(|_| httpcodes::HttpMethodNotAllowed);
//! }) //! })
//! .finish(); //! .finish();
//! } //! }
@ -58,7 +58,7 @@ 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 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
@ -110,7 +110,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() HttpBadRequest.build().body(format!("{}", self)).unwrap()
} }
} }
@ -219,7 +219,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(HttpOk);
resource.middleware(self); resource.middleware(self);
} }
@ -307,7 +307,7 @@ impl<S> Middleware<S> for Cors {
}; };
Ok(Started::Response( Ok(Started::Response(
HTTPOk.build() HttpOk.build()
.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());})
@ -823,7 +823,7 @@ mod tests {
.method(Method::OPTIONS) .method(Method::OPTIONS)
.finish(); .finish();
let resp: HttpResponse = HTTPOk.into(); let resp: HttpResponse = HttpOk.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"*"[..],
@ -832,7 +832,7 @@ 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 = HttpOk.build()
.header(header::VARY, "Accept") .header(header::VARY, "Accept")
.finish().unwrap(); .finish().unwrap();
let resp = cors.response(&mut req, resp).unwrap().response(); let resp = cors.response(&mut req, resp).unwrap().response();
@ -844,7 +844,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 = HttpOk.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,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(Method::GET).f(|_| httpcodes::HTTPOk); /// r.method(Method::GET).f(|_| httpcodes::HttpOk);
/// r.method(Method::HEAD).f(|_| httpcodes::HTTPMethodNotAllowed); /// r.method(Method::HEAD).f(|_| httpcodes::HttpMethodNotAllowed);
/// }) /// })
/// .finish(); /// .finish();
/// } /// }

View File

@ -29,7 +29,7 @@ pub trait Predicate<S> {
/// 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)); /// .h(HttpMethodNotAllowed));
/// } /// }
/// ``` /// ```
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>
@ -73,7 +73,7 @@ impl<S: 'static> Predicate<S> for AnyPredicate<S> {
/// .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)); /// .h(HttpMethodNotAllowed));
/// } /// }
/// ``` /// ```
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

@ -8,7 +8,7 @@ use pred::Predicate;
use handler::{Reply, ReplyItem, Handler, use handler::{Reply, ReplyItem, Handler,
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 httpcodes::HttpNotFound;
use httprequest::HttpRequest; use httprequest::HttpRequest;
use httpresponse::HttpResponse; use httpresponse::HttpResponse;
@ -26,7 +26,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(|_| HttpNotFound),
} }
} }
} }
@ -67,7 +67,7 @@ impl<S: 'static> Route<S> {
/// 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| HttpOk)
/// ) /// )
/// # .finish(); /// # .finish();
/// # } /// # }

View File

@ -15,7 +15,7 @@ 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 httpcodes::HttpNotFound;
use httprequest::HttpRequest; use httprequest::HttpRequest;
use error::{ParseError, PayloadError, ResponseError}; use error::{ParseError, PayloadError, ResponseError};
use payload::{Payload, PayloadWriter, PayloadStatus}; use payload::{Payload, PayloadWriter, PayloadStatus};
@ -151,7 +151,7 @@ impl<T, H> Http1<T, H>
} }
self.tasks.push_back( self.tasks.push_back(
Entry {pipe: Pipeline::error(HTTPNotFound), Entry {pipe: Pipeline::error(HttpNotFound),
flags: EntryFlags::empty()}); flags: EntryFlags::empty()});
continue continue
}, },

View File

@ -18,7 +18,7 @@ use tokio_core::reactor::Timeout;
use pipeline::Pipeline; use pipeline::Pipeline;
use error::PayloadError; use error::PayloadError;
use httpcodes::HTTPNotFound; use httpcodes::HttpNotFound;
use httpmessage::HttpMessage; use httpmessage::HttpMessage;
use httprequest::HttpRequest; use httprequest::HttpRequest;
use payload::{Payload, PayloadWriter, PayloadStatus}; use payload::{Payload, PayloadWriter, PayloadStatus};
@ -298,7 +298,7 @@ impl Entry {
} }
} }
Entry {task: task.unwrap_or_else(|| Pipeline::error(HTTPNotFound)), Entry {task: task.unwrap_or_else(|| Pipeline::error(HttpNotFound)),
payload: psender, payload: psender,
stream: H2Writer::new(resp, settings.get_shared_bytes()), stream: H2Writer::new(resp, settings.get_shared_bytes()),
flags: EntryFlags::empty(), flags: EntryFlags::empty(),

View File

@ -261,7 +261,7 @@ impl<H: IntoHttpHandler> HttpServer<H>
/// ///
/// HttpServer::new( /// HttpServer::new(
/// || Application::new() /// || Application::new()
/// .resource("/", |r| r.h(httpcodes::HTTPOk))) /// .resource("/", |r| r.h(httpcodes::HttpOk)))
/// .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));
@ -312,7 +312,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(httpcodes::HttpOk)))
/// .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

@ -41,7 +41,7 @@ use client::{ClientRequest, ClientRequestBuilder};
/// # use actix_web::*; /// # use actix_web::*;
/// # /// #
/// # fn my_handler(req: HttpRequest) -> HttpResponse { /// # fn my_handler(req: HttpRequest) -> HttpResponse {
/// # httpcodes::HTTPOk.into() /// # httpcodes::HttpOk.into()
/// # } /// # }
/// # /// #
/// # fn main() { /// # fn main() {
@ -282,9 +282,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() /// httpcodes::HttpOk.into()
/// } else { /// } else {
/// httpcodes::HTTPBadRequest.into() /// httpcodes::HttpBadRequest.into()
/// } /// }
/// } /// }
/// ///

View File

@ -55,7 +55,7 @@ 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}; use httpcodes::{HttpBadRequest, HttpMethodNotAllowed};
mod frame; mod frame;
mod proto; mod proto;
@ -139,22 +139,22 @@ impl ResponseError for WsHandshakeError {
fn error_response(&self) -> HttpResponse { fn error_response(&self) -> HttpResponse {
match *self { match *self {
WsHandshakeError::GetMethodRequired => { WsHandshakeError::GetMethodRequired => {
HTTPMethodNotAllowed HttpMethodNotAllowed
.build() .build()
.header(header::ALLOW, "GET") .header(header::ALLOW, "GET")
.finish() .finish()
.unwrap() .unwrap()
} }
WsHandshakeError::NoWebsocketUpgrade => WsHandshakeError::NoWebsocketUpgrade =>
HTTPBadRequest.with_reason("No WebSocket UPGRADE header found"), HttpBadRequest.with_reason("No WebSocket UPGRADE header found"),
WsHandshakeError::NoConnectionUpgrade => WsHandshakeError::NoConnectionUpgrade =>
HTTPBadRequest.with_reason("No CONNECTION upgrade"), HttpBadRequest.with_reason("No CONNECTION upgrade"),
WsHandshakeError::NoVersionHeader => WsHandshakeError::NoVersionHeader =>
HTTPBadRequest.with_reason("Websocket version header is required"), HttpBadRequest.with_reason("Websocket version header is required"),
WsHandshakeError::UnsupportedVersion => WsHandshakeError::UnsupportedVersion =>
HTTPBadRequest.with_reason("Unsupported version"), HttpBadRequest.with_reason("Unsupported version"),
WsHandshakeError::BadWebsocketKey => WsHandshakeError::BadWebsocketKey =>
HTTPBadRequest.with_reason("Handshake error"), HttpBadRequest.with_reason("Handshake error"),
} }
} }
} }