1
0
Fork 0
mirror of https://github.com/actix/actix-web.git synced 2024-11-23 01:51:11 +00: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()`
* Better naming for http codes
* Fix payload parse in situation when socket data is not ready.
* Fix Session mutable borrow lifetime #87

View file

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

View file

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

View file

@ -49,12 +49,12 @@ fn main() {
HttpServer::new(|| vec![
Application::new()
.prefix("/app1")
.resource("/", |r| r.f(|r| httpcodes::HTTPOk)),
.resource("/", |r| r.f(|r| httpcodes::HttpOk)),
Application::new()
.prefix("/app2")
.resource("/", |r| r.f(|r| httpcodes::HTTPOk)),
.resource("/", |r| r.f(|r| httpcodes::HttpOk)),
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(
|| Application::new()
.resource("/", |r| r.h(httpcodes::HTTPOk)))
.resource("/", |r| r.h(httpcodes::HttpOk)))
.bind("127.0.0.1:59080").unwrap()
.start();
@ -57,7 +57,7 @@ fn main() {
let sys = actix::System::new("http-server");
let addr = HttpServer::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")
.shutdown_timeout(60) // <- Set shutdown timeout to 60 seconds
.start();
@ -85,7 +85,7 @@ use actix_web::*;
fn main() {
HttpServer::new(
|| Application::new()
.resource("/", |r| r.h(httpcodes::HTTPOk)))
.resource("/", |r| r.h(httpcodes::HttpOk)))
.threads(4); // <- Start 4 workers
}
```
@ -146,7 +146,7 @@ use actix_web::*;
fn main() {
HttpServer::new(||
Application::new()
.resource("/", |r| r.h(httpcodes::HTTPOk)))
.resource("/", |r| r.h(httpcodes::HttpOk)))
.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
`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*
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.
@ -165,7 +165,7 @@ and is on for *HTTP/1.1* and "HTTP/2.0".
use actix_web::*;
fn index(req: HttpRequest) -> HttpResponse {
HTTPOk.build()
HttpOk.build()
.connection_type(headers::ConnectionType::Close) // <- Close connection
.force_close() // <- Alternative method
.finish().unwrap()

View file

@ -65,7 +65,7 @@ impl<S> Handler<S> for MyHandler {
/// Handle request
fn handle(&mut self, req: HttpRequest<S>) -> Self::Result {
self.0 += 1;
httpcodes::HTTPOk.into()
httpcodes::HttpOk.into()
}
}
# fn main() {}
@ -90,7 +90,7 @@ impl<S> Handler<S> for MyHandler {
/// Handle request
fn handle(&mut self, req: HttpRequest<S>) -> Self::Result {
self.0.fetch_add(1, Ordering::Relaxed);
httpcodes::HTTPOk.into()
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.
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.
```rust

View file

@ -32,7 +32,7 @@ fn main() {
Application::new()
.resource("/prefix", |r| r.f(index))
.resource("/user/{name}",
|r| r.method(Method::GET).f(|req| HTTPOk))
|r| r.method(Method::GET).f(|req| HttpOk))
.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.
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
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
resource registration and route registration. Resource matches all routes it contains in
@ -70,7 +70,7 @@ fn main() {
resource.route()
.filter(pred::Get())
.filter(pred::Header("content-type", "text/plain"))
.f(|req| HTTPOk)
.f(|req| HttpOk)
)
.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 {
let url = req.url_for("foo", &["1", "2", "3"]); // <- generate url for "foo" resource
HTTPOk.into()
HttpOk.into()
}
fn main() {
let app = Application::new()
.resource("/test/{a}/{b}/{c}", |r| {
r.name("foo"); // <- set resource name, then it could be used in `url_for`
r.method(Method::GET).f(|_| httpcodes::HTTPOk);
r.method(Method::GET).f(|_| httpcodes::HttpOk);
})
.finish();
}
@ -367,7 +367,7 @@ use actix_web::*;
fn index(mut req: HttpRequest) -> Result<HttpResponse> {
let url = req.url_for("youtube", &["oHg5SJYRHA0"])?;
assert_eq!(url.as_str(), "https://youtube.com/watch/oHg5SJYRHA0");
Ok(httpcodes::HTTPOk.into())
Ok(httpcodes::HttpOk.into())
}
fn main() {
@ -404,7 +404,7 @@ This handler designed to be use as a handler for application's *default resource
# use actix_web::*;
#
# fn index(req: HttpRequest) -> httpcodes::StaticResponse {
# httpcodes::HTTPOk
# httpcodes::HttpOk
# }
fn main() {
let app = Application::new()
@ -429,7 +429,7 @@ It is possible to register path normalization only for *GET* requests only
# use actix_web::*;
#
# fn index(req: HttpRequest) -> httpcodes::StaticResponse {
# httpcodes::HTTPOk
# httpcodes::HttpOk
# }
fn main() {
let app = Application::new()
@ -503,7 +503,7 @@ fn main() {
.resource("/index.html", |r|
r.route()
.filter(ContentTypeHeader)
.h(HTTPOk));
.h(HttpOk));
}
```
@ -531,7 +531,7 @@ fn main() {
.resource("/index.html", |r|
r.route()
.filter(pred::Not(pred::Get()))
.f(|req| HTTPMethodNotAllowed))
.f(|req| HttpMethodNotAllowed))
.finish();
}
```
@ -567,8 +567,8 @@ use actix_web::httpcodes::*;
fn main() {
Application::new()
.default_resource(|r| {
r.method(Method::GET).f(|req| HTTPNotFound);
r.route().filter(pred::Not(pred::Get())).f(|req| HTTPMethodNotAllowed);
r.method(Method::GET).f(|req| HttpNotFound);
r.route().filter(pred::Not(pred::Get())).f(|req| HttpMethodNotAllowed);
})
# .finish();
}

View file

@ -84,7 +84,7 @@ fn index(mut req: HttpRequest) -> Box<Future<Item=HttpResponse, Error=Error>> {
req.json().from_err()
.and_then(|val: MyObj| {
println!("model: {:?}", val);
Ok(httpcodes::HTTPOk.build().json(val)?) // <- send response
Ok(httpcodes::HttpOk.build().json(val)?) // <- send response
})
.responder()
}
@ -117,7 +117,7 @@ fn index(req: HttpRequest) -> Box<Future<Item=HttpResponse, Error=Error>> {
// synchronous workflow
.and_then(|body| { // <- body is loaded, now we can deserialize json
let obj = serde_json::from_slice::<MyObj>(&body)?;
Ok(httpcodes::HTTPOk.build().json(obj)?) // <- send response
Ok(httpcodes::HttpOk.build().json(obj)?) // <- send response
})
.responder()
}
@ -251,7 +251,7 @@ fn index(mut req: HttpRequest) -> Box<Future<Item=HttpResponse, Error=Error>> {
.from_err()
.and_then(|params| { // <- url encoded parameters
println!("==== BODY ==== {:?}", params);
ok(httpcodes::HTTPOk.into())
ok(httpcodes::HttpOk.into())
})
.responder()
}

View file

@ -20,10 +20,10 @@ use actix_web::test::TestRequest;
fn index(req: HttpRequest) -> HttpResponse {
if let Some(hdr) = req.headers().get(header::CONTENT_TYPE) {
if let Ok(s) = hdr.to_str() {
return httpcodes::HTTPOk.into()
return httpcodes::HttpOk.into()
}
}
httpcodes::HTTPBadRequest.into()
httpcodes::HttpBadRequest.into()
}
fn main() {
@ -59,16 +59,16 @@ use actix_web::*;
use actix_web::test::TestServer;
fn index(req: HttpRequest) -> HttpResponse {
httpcodes::HTTPOk.into()
httpcodes::HttpOk.into()
}
fn main() {
let mut srv = TestServer::new(|app| app.handler(index)); // <- Start new test server
let request = srv.get().finish().unwrap(); // <- create client request
let response = srv.execute(request.send()).unwrap(); // <- send request to the server
assert!(response.status().is_success()); // <- check response
let bytes = srv.execute(response.body()).unwrap(); // <- read response body
}
```
@ -84,7 +84,7 @@ use actix_web::*;
use actix_web::test::TestServer;
fn index(req: HttpRequest) -> HttpResponse {
httpcodes::HTTPOk.into()
httpcodes::HttpOk.into()
}
/// This function get called by http server.

View file

@ -183,8 +183,8 @@ impl<S> Application<S> where S: 'static {
/// let app = Application::new()
/// .prefix("/app")
/// .resource("/test", |r| {
/// r.method(Method::GET).f(|_| httpcodes::HTTPOk);
/// r.method(Method::HEAD).f(|_| httpcodes::HTTPMethodNotAllowed);
/// r.method(Method::GET).f(|_| httpcodes::HttpOk);
/// r.method(Method::HEAD).f(|_| httpcodes::HttpMethodNotAllowed);
/// })
/// .finish();
/// }
@ -226,8 +226,8 @@ impl<S> Application<S> where S: 'static {
/// fn main() {
/// let app = Application::new()
/// .resource("/test", |r| {
/// r.method(Method::GET).f(|_| httpcodes::HTTPOk);
/// r.method(Method::HEAD).f(|_| httpcodes::HTTPMethodNotAllowed);
/// r.method(Method::GET).f(|_| httpcodes::HttpOk);
/// 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> {
/// let url = req.url_for("youtube", &["oHg5SJYRHA0"])?;
/// assert_eq!(url.as_str(), "https://youtube.com/watch/oHg5SJYRHA0");
/// Ok(httpcodes::HTTPOk.into())
/// Ok(httpcodes::HttpOk.into())
/// }
///
/// fn main() {
@ -320,9 +320,9 @@ impl<S> Application<S> where S: 'static {
/// let app = Application::new()
/// .handler("/app", |req: HttpRequest| {
/// match *req.method() {
/// Method::GET => httpcodes::HTTPOk,
/// Method::POST => httpcodes::HTTPMethodNotAllowed,
/// _ => httpcodes::HTTPNotFound,
/// Method::GET => httpcodes::HttpOk,
/// Method::POST => httpcodes::HttpMethodNotAllowed,
/// _ => httpcodes::HttpNotFound,
/// }});
/// }
/// ```
@ -394,11 +394,11 @@ impl<S> Application<S> where S: 'static {
/// HttpServer::new(|| { vec![
/// Application::with_state(State1)
/// .prefix("/app1")
/// .resource("/", |r| r.h(httpcodes::HTTPOk))
/// .resource("/", |r| r.h(httpcodes::HttpOk))
/// .boxed(),
/// Application::with_state(State2)
/// .prefix("/app2")
/// .resource("/", |r| r.h(httpcodes::HTTPOk))
/// .resource("/", |r| r.h(httpcodes::HttpOk))
/// .boxed() ]})
/// .bind("127.0.0.1:8080").unwrap()
/// .run()
@ -459,7 +459,7 @@ mod tests {
#[test]
fn test_default_resource() {
let mut app = Application::new()
.resource("/test", |r| r.h(httpcodes::HTTPOk))
.resource("/test", |r| r.h(httpcodes::HttpOk))
.finish();
let req = TestRequest::with_uri("/test").finish();
@ -471,7 +471,7 @@ mod tests {
assert_eq!(resp.as_response().unwrap().status(), StatusCode::NOT_FOUND);
let mut app = Application::new()
.default_resource(|r| r.h(httpcodes::HTTPMethodNotAllowed))
.default_resource(|r| r.h(httpcodes::HttpMethodNotAllowed))
.finish();
let req = TestRequest::with_uri("/blah").finish();
let resp = app.run(req);
@ -482,7 +482,7 @@ mod tests {
fn test_unhandled_prefix() {
let mut app = Application::new()
.prefix("/test")
.resource("/test", |r| r.h(httpcodes::HTTPOk))
.resource("/test", |r| r.h(httpcodes::HttpOk))
.finish();
assert!(app.handle(HttpRequest::default()).is_err());
}
@ -490,7 +490,7 @@ mod tests {
#[test]
fn test_state() {
let mut app = Application::with_state(10)
.resource("/", |r| r.h(httpcodes::HTTPOk))
.resource("/", |r| r.h(httpcodes::HttpOk))
.finish();
let req = HttpRequest::default().with_state(Rc::clone(&app.state), app.router.clone());
let resp = app.run(req);
@ -501,7 +501,7 @@ mod tests {
fn test_prefix() {
let mut app = Application::new()
.prefix("/test")
.resource("/blah", |r| r.h(httpcodes::HTTPOk))
.resource("/blah", |r| r.h(httpcodes::HttpOk))
.finish();
let req = TestRequest::with_uri("/test").finish();
let resp = app.handle(req);
@ -523,7 +523,7 @@ mod tests {
#[test]
fn test_handler() {
let mut app = Application::new()
.handler("/test", httpcodes::HTTPOk)
.handler("/test", httpcodes::HttpOk)
.finish();
let req = TestRequest::with_uri("/test").finish();
@ -551,7 +551,7 @@ mod tests {
fn test_handler_prefix() {
let mut app = Application::new()
.prefix("/app")
.handler("/test", httpcodes::HTTPOk)
.handler("/test", httpcodes::HttpOk)
.finish();
let req = TestRequest::with_uri("/test").finish();

View file

@ -516,7 +516,7 @@ impl ClientRequestBuilder {
self.header(header::ACCEPT_ENCODING, "gzip, deflate");
}
}
let mut request = self.request.take().expect("cannot reuse request builder");
// set cookies

View file

@ -24,7 +24,7 @@ use body::Body;
use handler::Responder;
use httprequest::HttpRequest;
use httpresponse::HttpResponse;
use httpcodes::{self, HTTPExpectationFailed};
use httpcodes::{self, HttpExpectationFailed};
/// A specialized [`Result`](https://doc.rust-lang.org/std/result/enum.Result.html)
/// for actix web operations
@ -336,7 +336,7 @@ pub enum ExpectError {
impl ResponseError for ExpectError {
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 {
match *self {
UrlencodedError::Overflow => httpcodes::HTTPPayloadTooLarge.into(),
UrlencodedError::UnknownLength => httpcodes::HTTPLengthRequired.into(),
_ => httpcodes::HTTPBadRequest.into(),
UrlencodedError::Overflow => httpcodes::HttpPayloadTooLarge.into(),
UrlencodedError::UnknownLength => httpcodes::HttpLengthRequired.into(),
_ => httpcodes::HttpBadRequest.into(),
}
}
}
@ -421,8 +421,8 @@ impl ResponseError for JsonPayloadError {
fn error_response(&self) -> HttpResponse {
match *self {
JsonPayloadError::Overflow => httpcodes::HTTPPayloadTooLarge.into(),
_ => httpcodes::HTTPBadRequest.into(),
JsonPayloadError::Overflow => httpcodes::HttpPayloadTooLarge.into(),
_ => httpcodes::HttpBadRequest.into(),
}
}
}

View file

@ -15,7 +15,7 @@ use handler::{Handler, Responder};
use headers::ContentEncoding;
use httprequest::HttpRequest;
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
/// file extension.
@ -84,7 +84,7 @@ impl Responder for NamedFile {
type Error = 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);
if let Some(ext) = self.path().extension() {
let mime = get_mime_type(&ext.to_string_lossy());
@ -164,7 +164,7 @@ impl Responder for Directory {
<ul>\
{}\
</ul></body>\n</html>", index_of, index_of, body);
Ok(HTTPOk.build()
Ok(HttpOk.build()
.content_type("text/html; charset=utf-8")
.body(html).unwrap())
}
@ -289,7 +289,7 @@ impl<S> Handler<S> for StaticFiles {
}
new_path.push_str(redir_index);
Ok(FilesystemElement::Redirect(
HTTPFound
HttpFound
.build()
.header::<_, &str>("LOCATION", &new_path)
.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::*;
/// #
/// # fn index(req: HttpRequest) -> httpcodes::StaticResponse {
/// # httpcodes::HTTPOk
/// # httpcodes::HttpOk
/// # }
/// fn main() {
/// let app = Application::new()

View file

@ -7,67 +7,174 @@ use handler::{Reply, Handler, RouteHandler, Responder};
use httprequest::HttpRequest;
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);
#[doc(hidden)]
pub const HTTPCreated: StaticResponse = StaticResponse(StatusCode::CREATED);
#[doc(hidden)]
pub const HTTPAccepted: StaticResponse = StaticResponse(StatusCode::ACCEPTED);
#[doc(hidden)]
pub const HTTPNonAuthoritativeInformation: StaticResponse =
StaticResponse(StatusCode::NON_AUTHORITATIVE_INFORMATION);
#[doc(hidden)]
pub const HTTPNoContent: StaticResponse = StaticResponse(StatusCode::NO_CONTENT);
#[doc(hidden)]
pub const HTTPResetContent: StaticResponse = StaticResponse(StatusCode::RESET_CONTENT);
#[doc(hidden)]
pub const HTTPPartialContent: StaticResponse = StaticResponse(StatusCode::PARTIAL_CONTENT);
#[doc(hidden)]
pub const HTTPMultiStatus: StaticResponse = StaticResponse(StatusCode::MULTI_STATUS);
#[doc(hidden)]
pub const HTTPAlreadyReported: StaticResponse = StaticResponse(StatusCode::ALREADY_REPORTED);
#[doc(hidden)]
pub const HTTPMultipleChoices: StaticResponse = StaticResponse(StatusCode::MULTIPLE_CHOICES);
#[doc(hidden)]
pub const HTTPMovedPermanenty: StaticResponse = StaticResponse(StatusCode::MOVED_PERMANENTLY);
#[doc(hidden)]
pub const HTTPFound: StaticResponse = StaticResponse(StatusCode::FOUND);
#[doc(hidden)]
pub const HTTPSeeOther: StaticResponse = StaticResponse(StatusCode::SEE_OTHER);
#[doc(hidden)]
pub const HTTPNotModified: StaticResponse = StaticResponse(StatusCode::NOT_MODIFIED);
#[doc(hidden)]
pub const HTTPUseProxy: StaticResponse = StaticResponse(StatusCode::USE_PROXY);
#[doc(hidden)]
pub const HTTPTemporaryRedirect: StaticResponse =
StaticResponse(StatusCode::TEMPORARY_REDIRECT);
#[doc(hidden)]
pub const HTTPPermanentRedirect: StaticResponse =
StaticResponse(StatusCode::PERMANENT_REDIRECT);
#[doc(hidden)]
pub const HTTPBadRequest: StaticResponse = StaticResponse(StatusCode::BAD_REQUEST);
#[doc(hidden)]
pub const HTTPUnauthorized: StaticResponse = StaticResponse(StatusCode::UNAUTHORIZED);
#[doc(hidden)]
pub const HTTPPaymentRequired: StaticResponse = StaticResponse(StatusCode::PAYMENT_REQUIRED);
#[doc(hidden)]
pub const HTTPForbidden: StaticResponse = StaticResponse(StatusCode::FORBIDDEN);
#[doc(hidden)]
pub const HTTPNotFound: StaticResponse = StaticResponse(StatusCode::NOT_FOUND);
#[doc(hidden)]
pub const HTTPMethodNotAllowed: StaticResponse =
StaticResponse(StatusCode::METHOD_NOT_ALLOWED);
#[doc(hidden)]
pub const HTTPNotAcceptable: StaticResponse = StaticResponse(StatusCode::NOT_ACCEPTABLE);
#[doc(hidden)]
pub const HTTPProxyAuthenticationRequired: StaticResponse =
StaticResponse(StatusCode::PROXY_AUTHENTICATION_REQUIRED);
#[doc(hidden)]
pub const HTTPRequestTimeout: StaticResponse = StaticResponse(StatusCode::REQUEST_TIMEOUT);
#[doc(hidden)]
pub const HTTPConflict: StaticResponse = StaticResponse(StatusCode::CONFLICT);
#[doc(hidden)]
pub const HTTPGone: StaticResponse = StaticResponse(StatusCode::GONE);
#[doc(hidden)]
pub const HTTPLengthRequired: StaticResponse = StaticResponse(StatusCode::LENGTH_REQUIRED);
#[doc(hidden)]
pub const HTTPPreconditionFailed: StaticResponse =
StaticResponse(StatusCode::PRECONDITION_FAILED);
#[doc(hidden)]
pub const HTTPPayloadTooLarge: StaticResponse = StaticResponse(StatusCode::PAYLOAD_TOO_LARGE);
#[doc(hidden)]
pub const HTTPUriTooLong: StaticResponse = StaticResponse(StatusCode::URI_TOO_LONG);
#[doc(hidden)]
pub const HTTPUnsupportedMediaType: StaticResponse =
StaticResponse(StatusCode::UNSUPPORTED_MEDIA_TYPE);
#[doc(hidden)]
pub const HTTPRangeNotSatisfiable: StaticResponse =
StaticResponse(StatusCode::RANGE_NOT_SATISFIABLE);
#[doc(hidden)]
pub const HTTPExpectationFailed: StaticResponse =
StaticResponse(StatusCode::EXPECTATION_FAILED);
#[doc(hidden)]
pub const HTTPInternalServerError: StaticResponse =
StaticResponse(StatusCode::INTERNAL_SERVER_ERROR);
#[doc(hidden)]
pub const HTTPNotImplemented: StaticResponse = StaticResponse(StatusCode::NOT_IMPLEMENTED);
#[doc(hidden)]
pub const HTTPBadGateway: StaticResponse = StaticResponse(StatusCode::BAD_GATEWAY);
#[doc(hidden)]
pub const HTTPServiceUnavailable: StaticResponse =
StaticResponse(StatusCode::SERVICE_UNAVAILABLE);
#[doc(hidden)]
pub const HTTPGatewayTimeout: StaticResponse =
StaticResponse(StatusCode::GATEWAY_TIMEOUT);
#[doc(hidden)]
pub const HTTPVersionNotSupported: StaticResponse =
StaticResponse(StatusCode::HTTP_VERSION_NOT_SUPPORTED);
#[doc(hidden)]
pub const HTTPVariantAlsoNegotiates: StaticResponse =
StaticResponse(StatusCode::VARIANT_ALSO_NEGOTIATES);
#[doc(hidden)]
pub const HTTPInsufficientStorage: StaticResponse =
StaticResponse(StatusCode::INSUFFICIENT_STORAGE);
#[doc(hidden)]
pub const HTTPLoopDetected: StaticResponse = StaticResponse(StatusCode::LOOP_DETECTED);

View file

@ -114,7 +114,7 @@ pub trait HttpMessage {
/// .from_err()
/// .and_then(|bytes: Bytes| { // <- complete body
/// println!("==== BODY ==== {:?}", bytes);
/// Ok(httpcodes::HTTPOk.into())
/// Ok(httpcodes::HttpOk.into())
/// }).responder()
/// }
/// # fn main() {}
@ -148,7 +148,7 @@ pub trait HttpMessage {
/// .from_err()
/// .and_then(|params| { // <- url encoded parameters
/// println!("==== BODY ==== {:?}", params);
/// ok(httpcodes::HTTPOk.into())
/// ok(httpcodes::HttpOk.into())
/// })
/// .responder()
/// }
@ -187,7 +187,7 @@ pub trait HttpMessage {
/// .from_err()
/// .and_then(|val: MyObj| { // <- deserialized value
/// println!("==== BODY ==== {:?}", val);
/// Ok(httpcodes::HTTPOk.into())
/// Ok(httpcodes::HttpOk.into())
/// }).responder()
/// }
/// # fn main() {}

View file

@ -249,14 +249,14 @@ impl<S> HttpRequest<S> {
/// #
/// fn index(req: HttpRequest) -> HttpResponse {
/// let url = req.url_for("foo", &["1", "2", "3"]); // <- generate url for "foo" resource
/// HTTPOk.into()
/// HttpOk.into()
/// }
///
/// fn main() {
/// let app = Application::new()
/// .resource("/test/{one}/{two}/{three}", |r| {
/// r.name("foo"); // <- set resource name, then it could be used in `url_for`
/// r.method(Method::GET).f(|_| httpcodes::HTTPOk);
/// r.method(Method::GET).f(|_| httpcodes::HttpOk);
/// })
/// .finish();
/// }

View file

@ -252,7 +252,7 @@ impl HttpResponseBuilder {
/// use http::header;
///
/// fn index(req: HttpRequest) -> Result<HttpResponse> {
/// Ok(HTTPOk.build()
/// Ok(HttpOk.build()
/// .header("X-TEST", "value")
/// .header(header::CONTENT_TYPE, "application/json")
/// .finish()?)
@ -372,7 +372,7 @@ impl HttpResponseBuilder {
/// use actix_web::headers::Cookie;
///
/// fn index(req: HttpRequest) -> Result<HttpResponse> {
/// Ok(HTTPOk.build()
/// Ok(HttpOk.build()
/// .cookie(
/// Cookie::build("name", "value")
/// .domain("www.rust-lang.org")
@ -753,7 +753,7 @@ mod tests {
Method::GET, Uri::from_str("/").unwrap(), Version::HTTP_11, headers, None);
let cookies = req.cookies().unwrap();
let resp = httpcodes::HTTPOk
let resp = httpcodes::HttpOk
.build()
.cookie(headers::Cookie::build("name", "value")
.domain("www.rust-lang.org")

View file

@ -75,7 +75,7 @@ impl<T: Serialize> Responder for Json<T> {
/// .from_err()
/// .and_then(|val: MyObj| { // <- deserialized value
/// println!("==== BODY ==== {:?}", val);
/// Ok(httpcodes::HTTPOk.into())
/// Ok(httpcodes::HttpOk.into())
/// }).responder()
/// }
/// # fn main() {}

View file

@ -38,8 +38,8 @@
//! .max_age(3600)
//! .finish().expect("Can not create CORS middleware")
//! .register(r); // <- Register CORS middleware
//! r.method(Method::GET).f(|_| httpcodes::HTTPOk);
//! r.method(Method::HEAD).f(|_| httpcodes::HTTPMethodNotAllowed);
//! r.method(Method::GET).f(|_| httpcodes::HttpOk);
//! r.method(Method::HEAD).f(|_| httpcodes::HttpMethodNotAllowed);
//! })
//! .finish();
//! }
@ -58,7 +58,7 @@ use resource::Resource;
use httpmessage::HttpMessage;
use httprequest::HttpRequest;
use httpresponse::HttpResponse;
use httpcodes::{HTTPOk, HTTPBadRequest};
use httpcodes::{HttpOk, HttpBadRequest};
use middleware::{Middleware, Response, Started};
/// A set of errors that can occur during processing CORS
@ -110,7 +110,7 @@ pub enum CorsBuilderError {
impl ResponseError for CorsError {
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*
/// requests.
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);
}
@ -307,7 +307,7 @@ impl<S> Middleware<S> for Cors {
};
Ok(Started::Response(
HTTPOk.build()
HttpOk.build()
.if_some(self.max_age.as_ref(), |max_age, resp| {
let _ = resp.header(
header::ACCESS_CONTROL_MAX_AGE, format!("{}", max_age).as_str());})
@ -823,7 +823,7 @@ mod tests {
.method(Method::OPTIONS)
.finish();
let resp: HttpResponse = HTTPOk.into();
let resp: HttpResponse = HttpOk.into();
let resp = cors.response(&mut req, resp).unwrap().response();
assert_eq!(
&b"*"[..],
@ -832,7 +832,7 @@ mod tests {
&b"Origin"[..],
resp.headers().get(header::VARY).unwrap().as_bytes());
let resp: HttpResponse = HTTPOk.build()
let resp: HttpResponse = HttpOk.build()
.header(header::VARY, "Accept")
.finish().unwrap();
let resp = cors.response(&mut req, resp).unwrap().response();
@ -844,7 +844,7 @@ mod tests {
.disable_vary_header()
.allowed_origin("https://www.example.com")
.finish().unwrap();
let resp: HttpResponse = HTTPOk.into();
let resp: HttpResponse = HttpOk.into();
let resp = cors.response(&mut req, resp).unwrap().response();
assert_eq!(
&b"https://www.example.com"[..],

View file

@ -22,8 +22,8 @@ use middleware::{Response, Middleware};
/// .header("X-Version", "0.2")
/// .finish())
/// .resource("/test", |r| {
/// r.method(Method::GET).f(|_| httpcodes::HTTPOk);
/// r.method(Method::HEAD).f(|_| httpcodes::HTTPMethodNotAllowed);
/// r.method(Method::GET).f(|_| httpcodes::HttpOk);
/// r.method(Method::HEAD).f(|_| httpcodes::HttpMethodNotAllowed);
/// })
/// .finish();
/// }

View file

@ -29,7 +29,7 @@ pub trait Predicate<S> {
/// Application::new()
/// .resource("/index.html", |r| r.route()
/// .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>
@ -73,7 +73,7 @@ impl<S: 'static> Predicate<S> for AnyPredicate<S> {
/// .resource("/index.html", |r| r.route()
/// .filter(pred::All(pred::Get())
/// .and(pred::Header("content-type", "plain/text")))
/// .h(HTTPMethodNotAllowed));
/// .h(HttpMethodNotAllowed));
/// }
/// ```
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,
Responder, RouteHandler, AsyncHandler, WrapHandler};
use middleware::{Middleware, Response as MiddlewareResponse, Started as MiddlewareStarted};
use httpcodes::HTTPNotFound;
use httpcodes::HttpNotFound;
use httprequest::HttpRequest;
use httpresponse::HttpResponse;
@ -26,7 +26,7 @@ impl<S: 'static> Default for Route<S> {
fn default() -> Route<S> {
Route {
preds: Vec::new(),
handler: InnerHandler::new(|_| HTTPNotFound),
handler: InnerHandler::new(|_| HttpNotFound),
}
}
}
@ -67,7 +67,7 @@ impl<S: 'static> Route<S> {
/// r.route()
/// .filter(pred::Get())
/// .filter(pred::Header("content-type", "text/plain"))
/// .f(|req| HTTPOk)
/// .f(|req| HttpOk)
/// )
/// # .finish();
/// # }

View file

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

View file

@ -18,7 +18,7 @@ use tokio_core::reactor::Timeout;
use pipeline::Pipeline;
use error::PayloadError;
use httpcodes::HTTPNotFound;
use httpcodes::HttpNotFound;
use httpmessage::HttpMessage;
use httprequest::HttpRequest;
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,
stream: H2Writer::new(resp, settings.get_shared_bytes()),
flags: EntryFlags::empty(),

View file

@ -261,7 +261,7 @@ impl<H: IntoHttpHandler> HttpServer<H>
///
/// HttpServer::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")
/// .start();
/// # actix::Arbiter::system().do_send(actix::msgs::SystemExit(0));
@ -312,7 +312,7 @@ impl<H: IntoHttpHandler> HttpServer<H>
/// fn main() {
/// HttpServer::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")
/// .run();
/// }

View file

@ -41,7 +41,7 @@ use client::{ClientRequest, ClientRequestBuilder};
/// # use actix_web::*;
/// #
/// # fn my_handler(req: HttpRequest) -> HttpResponse {
/// # httpcodes::HTTPOk.into()
/// # httpcodes::HttpOk.into()
/// # }
/// #
/// # fn main() {
@ -282,9 +282,9 @@ impl<S: 'static> Iterator for TestApp<S> {
///
/// fn index(req: HttpRequest) -> HttpResponse {
/// if let Some(hdr) = req.headers().get(header::CONTENT_TYPE) {
/// httpcodes::HTTPOk.into()
/// httpcodes::HttpOk.into()
/// } else {
/// httpcodes::HTTPBadRequest.into()
/// httpcodes::HttpBadRequest.into()
/// }
/// }
///
@ -403,7 +403,7 @@ impl<S> TestRequest<S> {
self.payload = Some(payload);
self
}
/// Complete request creation and generate `HttpRequest` instance
pub fn finish(self) -> HttpRequest<S> {
let TestRequest { state, method, uri, version, headers, params, cookies, payload } = self;

View file

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