1
0
mirror of https://github.com/fafhrd91/actix-web synced 2025-07-04 18:06:23 +02:00

Compare commits

...

17 Commits

Author SHA1 Message Date
b640b49b05 adjust low buf size 2018-03-01 20:13:50 -08:00
1fea4bd9a6 prepare release 2018-03-01 20:01:25 -08:00
206c4e581a rename httpcodes 2018-03-01 19:12:59 -08:00
4e13505b92 rename .p to a .filter 2018-03-01 18:42:50 -08:00
5b6d7cddbf Fix payload parse in situation when socket data is not ready 2018-03-01 18:27:04 -08:00
4aaf9f08f8 update readme 2018-02-28 22:31:54 -08:00
b0ba23ff55 Merge pull request #88 from rofrol/patch-2
be consistent with host - had CORS preflight once
2018-02-28 17:07:57 -08:00
42b19b1819 Merge branch 'master' into patch-2 2018-02-28 17:07:44 -08:00
0335fde3f9 Update README.md 2018-02-28 16:58:05 -08:00
f27edbff89 be consistent with host - had CORS preflight once 2018-03-01 01:01:27 +01:00
d62d6e68e0 use new version of http crate 2018-02-28 14:16:55 -08:00
1284264511 Update CHANGES.md 2018-02-28 12:35:16 -08:00
d977fe563b Merge pull request #87 from adwhit/fix-session-set
fix session mut borrow lifetime
2018-02-28 12:34:46 -08:00
bb68f9dd90 add session borrow fix to changes 2018-02-28 19:52:53 +00:00
313396d9b5 fix session mut borrow lifetime 2018-02-28 19:35:26 +00:00
171a23561e export Drain 2018-02-28 11:10:54 -08:00
67f33a4760 add redis session example 2018-02-28 10:26:40 -08:00
39 changed files with 339 additions and 154 deletions

View File

@ -1,5 +1,16 @@
# Changes
## 0.4.1 (2018-03-01)
* 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
## 0.4.0 (2018-02-28)
* Actix 0.5 compatibility

View File

@ -1,8 +1,8 @@
[package]
name = "actix-web"
version = "0.4.0"
version = "0.4.1"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Actix web framework"
description = "Actix web is a small, pragmatic, extremely fast, web framework for Rust."
readme = "README.md"
keywords = ["http", "web", "framework", "async", "futures"]
homepage = "https://github.com/actix/actix-web"
@ -42,7 +42,7 @@ brotli2 = "^0.3.2"
failure = "0.1.1"
flate2 = "1.0"
h2 = "0.1"
http = "^0.1.2"
http = "^0.1.5"
httparse = "1.2"
http-range = "0.1"
libc = "0.2"
@ -108,6 +108,7 @@ members = [
"examples/hello-world",
"examples/multipart",
"examples/state",
"examples/redis-session",
"examples/template_tera",
"examples/tls",
"examples/websocket",

View File

@ -10,11 +10,13 @@ Actix web is a small, pragmatic, extremely fast, web framework for Rust.
* Configurable [request routing](https://actix.github.io/actix-web/guide/qs_5.html)
* Graceful server shutdown
* Multipart streams
* SSL support with openssl or native-tls
* Middlewares ([Logger](https://actix.github.io/actix-web/guide/qs_10.html#logging),
[Session](https://actix.github.io/actix-web/guide/qs_10.html#user-sessions),
[Redis sessions](https://github.com/actix/actix-redis),
[DefaultHeaders](https://actix.github.io/actix-web/guide/qs_10.html#default-headers),
[CORS](https://actix.github.io/actix-web/actix_web/middleware/cors/index.html))
* Built on top of [Actix](https://github.com/actix/actix).
* Built on top of [Actix actor framework](https://github.com/actix/actix).
## Documentation
@ -57,6 +59,9 @@ fn main() {
* [SockJS Server](https://github.com/actix/actix-sockjs)
* [Json](https://github.com/actix/actix-web/tree/master/examples/json/)
You may consider checking out
[this directory](https://github.com/actix/actix-web/tree/master/examples) for more examples.
## Benchmarks
* [TechEmpower Framework Benchmark](https://www.techempower.com/benchmarks/#section=data-r15&hw=ph&test=plaintext)

View File

@ -62,7 +62,7 @@ impl Handler<GraphQLData> for GraphQLExecutor {
}
fn graphiql(_req: HttpRequest<State>) -> Result<HttpResponse> {
let html = graphiql_source("http://localhost:8080/graphql");
let html = graphiql_source("http://127.0.0.1:8080/graphql");
Ok(HttpResponse::build(StatusCode::OK)
.content_type("text/html; charset=utf-8")
.body(html).unwrap())

View File

@ -0,0 +1,11 @@
[package]
name = "redis-session"
version = "0.1.0"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
workspace = "../.."
[dependencies]
env_logger = "0.5"
actix = "0.5"
actix-web = "0.4"
actix-redis = { version = "0.2", features = ["web"] }

View File

@ -0,0 +1,48 @@
#![allow(unused_variables)]
extern crate actix;
extern crate actix_web;
extern crate actix_redis;
extern crate env_logger;
use actix_web::*;
use actix_web::middleware::RequestSession;
use actix_redis::RedisSessionBackend;
/// simple handler
fn index(mut req: HttpRequest) -> Result<HttpResponse> {
println!("{:?}", req);
// session
if let Some(count) = req.session().get::<i32>("counter")? {
println!("SESSION value: {}", count);
req.session().set("counter", count+1)?;
} else {
req.session().set("counter", 1)?;
}
Ok("Welcome!".into())
}
fn main() {
::std::env::set_var("RUST_LOG", "actix_web=info,actix_redis=info");
env_logger::init();
let sys = actix::System::new("basic-example");
HttpServer::new(
|| Application::new()
// enable logger
.middleware(middleware::Logger::default())
// cookie session middleware
.middleware(middleware::SessionStorage::new(
RedisSessionBackend::new("127.0.0.1:6379", &[0; 32])
))
// register simple route, handle all methods
.resource("/", |r| r.f(index)))
.bind("0.0.0.0:8080").unwrap()
.threads(1)
.start();
let _ = sys.run();
}

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
@ -68,9 +68,9 @@ fn main() {
Application::new()
.resource("/path", |resource|
resource.route()
.p(pred::Get())
.p(pred::Header("content-type", "text/plain"))
.f(|req| HTTPOk)
.filter(pred::Get())
.filter(pred::Header("content-type", "text/plain"))
.f(|req| HttpOk)
)
.finish();
}
@ -85,7 +85,7 @@ If resource can not match any route "NOT FOUND" response get returned.
[*Route*](../actix_web/struct.Route.html) object. Route can be configured with
builder-like pattern. Following configuration methods are available:
* [*Route::p()*](../actix_web/struct.Route.html#method.p) method registers new predicate,
* [*Route::filter()*](../actix_web/struct.Route.html#method.filter) method registers new predicate,
any number of predicates could be registered for each route.
* [*Route::f()*](../actix_web/struct.Route.html#method.f) method registers handler function
@ -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()
@ -502,8 +502,8 @@ fn main() {
Application::new()
.resource("/index.html", |r|
r.route()
.p(ContentTypeHeader)
.h(HTTPOk));
.filter(ContentTypeHeader)
.h(HttpOk));
}
```
@ -530,8 +530,8 @@ fn main() {
Application::new()
.resource("/index.html", |r|
r.route()
.p(pred::Not(pred::Get()))
.f(|req| HTTPMethodNotAllowed))
.filter(pred::Not(pred::Get()))
.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().p(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,7 +59,7 @@ use actix_web::*;
use actix_web::test::TestServer;
fn index(req: HttpRequest) -> HttpResponse {
httpcodes::HTTPOk.into()
httpcodes::HttpOk.into()
}
fn main() {
@ -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

@ -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

@ -35,10 +35,11 @@
//! * `WebSockets` server/client
//! * Transparent content compression/decompression (br, gzip, deflate)
//! * Configurable request routing
//! * Multipart streams
//! * Middlewares (`Logger`, `Session`, `CORS`, `DefaultHeaders`)
//! * Graceful server shutdown
//! * Built on top of [Actix](https://github.com/actix/actix).
//! * Multipart streams
//! * SSL support with openssl or native-tls
//! * Middlewares (`Logger`, `Session`, `CORS`, `DefaultHeaders`)
//! * Built on top of [Actix actor framework](https://github.com/actix/actix).
#![cfg_attr(actix_nightly, feature(
specialization, // for impl ErrorResponse for std::error::Error
@ -188,6 +189,7 @@ pub mod dev {
//! ```
pub use body::BodyStream;
pub use context::Drain;
pub use info::ConnectionInfo;
pub use handler::Handler;
pub use json::JsonBody;

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

@ -86,7 +86,7 @@ impl<'a> Session<'a> {
}
/// Set a `value` from the session.
pub fn set<T: Serialize>(&'a mut self, key: &str, value: T) -> Result<()> {
pub fn set<T: Serialize>(&mut self, key: &str, value: T) -> Result<()> {
self.0.set(key, serde_json::to_string(&value)?);
Ok(())
}

View File

@ -28,8 +28,8 @@ pub trait Predicate<S> {
/// fn main() {
/// Application::new()
/// .resource("/index.html", |r| r.route()
/// .p(pred::Any(pred::Get()).or(pred::Post()))
/// .h(HTTPMethodNotAllowed));
/// .filter(pred::Any(pred::Get()).or(pred::Post()))
/// .h(HttpMethodNotAllowed));
/// }
/// ```
pub fn Any<S: 'static, P: Predicate<S> + 'static>(pred: P) -> AnyPredicate<S>
@ -71,9 +71,9 @@ impl<S: 'static> Predicate<S> for AnyPredicate<S> {
/// fn main() {
/// Application::new()
/// .resource("/index.html", |r| r.route()
/// .p(pred::All(pred::Get())
/// .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

@ -81,8 +81,8 @@ impl<S: 'static> Resource<S> {
/// let app = Application::new()
/// .resource(
/// "/", |r| r.route()
/// .p(pred::Any(pred::Get()).or(pred::Put()))
/// .p(pred::Header("Content-Type", "text/plain"))
/// .filter(pred::Any(pred::Get()).or(pred::Put()))
/// .filter(pred::Header("Content-Type", "text/plain"))
/// .f(|r| HttpResponse::Ok()))
/// .finish();
/// }
@ -97,11 +97,11 @@ impl<S: 'static> Resource<S> {
/// This is shortcut for:
///
/// ```rust,ignore
/// Resource::resource("/", |r| r.route().p(pred::Get()).f(index)
/// Resource::resource("/", |r| r.route().filter(pred::Get()).f(index)
/// ```
pub fn method(&mut self, method: Method) -> &mut Route<S> {
self.routes.push(Route::default());
self.routes.last_mut().unwrap().p(pred::Method(method))
self.routes.last_mut().unwrap().filter(pred::Method(method))
}
/// Register a new route and add handler object.

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),
}
}
}
@ -65,18 +65,24 @@ impl<S: 'static> Route<S> {
/// Application::new()
/// .resource("/path", |r|
/// r.route()
/// .p(pred::Get())
/// .p(pred::Header("content-type", "text/plain"))
/// .f(|req| HTTPOk)
/// .filter(pred::Get())
/// .filter(pred::Header("content-type", "text/plain"))
/// .f(|req| HttpOk)
/// )
/// # .finish();
/// # }
/// ```
pub fn p<T: Predicate<S> + 'static>(&mut self, p: T) -> &mut Self {
pub fn filter<T: Predicate<S> + 'static>(&mut self, p: T) -> &mut Self {
self.preds.push(Box::new(p));
self
}
#[doc(hidden)]
#[deprecated(since="0.4.1", note="please use `.filter()` instead")]
pub fn p<T: Predicate<S> + 'static>(&mut self, p: T) -> &mut Self {
self.filter(p)
}
/// Set handler object. Usually call to this method is last call
/// during route configuration, because it does not return reference to self.
pub fn h<H: Handler<S>>(&mut self, handler: H) {

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
},
@ -431,7 +431,7 @@ impl Reader {
break true
},
Ok(Async::NotReady) =>
break false,
return Ok(Async::NotReady),
Err(err) => {
payload.tx.set_error(err.into());
return Err(ReaderError::Payload)

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

@ -5,7 +5,7 @@ use futures::{Async, Poll};
use super::IoStream;
const LW_BUFFER_SIZE: usize = 4096;
const HW_BUFFER_SIZE: usize = 16_384;
const HW_BUFFER_SIZE: usize = 32_768;
pub fn read_from_io<T: IoStream>(io: &mut T, buf: &mut BytesMut) -> Poll<usize, io::Error> {

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()
/// }
/// }
///

View File

@ -197,11 +197,11 @@ impl WsClient {
self.request.upgrade();
self.request.set_header(header::UPGRADE, "websocket");
self.request.set_header(header::CONNECTION, "upgrade");
self.request.set_header("SEC-WEBSOCKET-VERSION", "13");
self.request.set_header(header::SEC_WEBSOCKET_VERSION, "13");
self.request.with_connector(self.conn.clone());
if let Some(protocols) = self.protocols.take() {
self.request.set_header("SEC-WEBSOCKET-PROTOCOL", protocols.as_str());
self.request.set_header(header::SEC_WEBSOCKET_PROTOCOL, protocols.as_str());
}
let request = match self.request.finish() {
Ok(req) => req,
@ -249,7 +249,7 @@ impl WsClientHandshake {
let key = base64::encode(&sec_key);
request.headers_mut().insert(
HeaderName::try_from("SEC-WEBSOCKET-KEY").unwrap(),
header::SEC_WEBSOCKET_KEY,
HeaderValue::try_from(key.as_str()).unwrap());
let (tx, rx) = unbounded();
@ -328,8 +328,7 @@ impl Future for WsClientHandshake {
return Err(WsClientError::MissingConnectionHeader)
}
if let Some(key) = resp.headers().get(
HeaderName::try_from("SEC-WEBSOCKET-ACCEPT").unwrap())
if let Some(key) = resp.headers().get(header::SEC_WEBSOCKET_ACCEPT)
{
// field is constructed by concatenating /key/
// with the string "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" (RFC 6455)

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;
@ -70,11 +70,6 @@ pub use self::context::WebsocketContext;
pub use self::client::{WsClient, WsClientError,
WsClientReader, WsClientWriter, WsClientHandshake};
const SEC_WEBSOCKET_ACCEPT: &str = "SEC-WEBSOCKET-ACCEPT";
const SEC_WEBSOCKET_KEY: &str = "SEC-WEBSOCKET-KEY";
const SEC_WEBSOCKET_VERSION: &str = "SEC-WEBSOCKET-VERSION";
// const SEC_WEBSOCKET_PROTOCOL: &'static str = "SEC-WEBSOCKET-PROTOCOL";
/// Websocket errors
#[derive(Fail, Debug)]
@ -144,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"),
}
}
}
@ -222,11 +217,11 @@ pub fn handshake<S>(req: &HttpRequest<S>) -> Result<HttpResponseBuilder, WsHands
}
// check supported version
if !req.headers().contains_key(SEC_WEBSOCKET_VERSION) {
if !req.headers().contains_key(header::SEC_WEBSOCKET_VERSION) {
return Err(WsHandshakeError::NoVersionHeader)
}
let supported_ver = {
if let Some(hdr) = req.headers().get(SEC_WEBSOCKET_VERSION) {
if let Some(hdr) = req.headers().get(header::SEC_WEBSOCKET_VERSION) {
hdr == "13" || hdr == "8" || hdr == "7"
} else {
false
@ -237,11 +232,11 @@ pub fn handshake<S>(req: &HttpRequest<S>) -> Result<HttpResponseBuilder, WsHands
}
// check client handshake for validity
if !req.headers().contains_key(SEC_WEBSOCKET_KEY) {
if !req.headers().contains_key(header::SEC_WEBSOCKET_KEY) {
return Err(WsHandshakeError::BadWebsocketKey)
}
let key = {
let key = req.headers().get(SEC_WEBSOCKET_KEY).unwrap();
let key = req.headers().get(header::SEC_WEBSOCKET_KEY).unwrap();
hash_key(key.as_ref())
};
@ -249,7 +244,7 @@ pub fn handshake<S>(req: &HttpRequest<S>) -> Result<HttpResponseBuilder, WsHands
.connection_type(ConnectionType::Upgrade)
.header(header::UPGRADE, "websocket")
.header(header::TRANSFER_ENCODING, "chunked")
.header(SEC_WEBSOCKET_ACCEPT, key.as_str())
.header(header::SEC_WEBSOCKET_ACCEPT, key.as_str())
.take())
}
@ -385,7 +380,7 @@ mod tests {
header::HeaderValue::from_static("websocket"));
headers.insert(header::CONNECTION,
header::HeaderValue::from_static("upgrade"));
headers.insert(SEC_WEBSOCKET_VERSION,
headers.insert(header::SEC_WEBSOCKET_VERSION,
header::HeaderValue::from_static("5"));
let req = HttpRequest::new(Method::GET, Uri::from_str("/").unwrap(),
Version::HTTP_11, headers, None);
@ -396,7 +391,7 @@ mod tests {
header::HeaderValue::from_static("websocket"));
headers.insert(header::CONNECTION,
header::HeaderValue::from_static("upgrade"));
headers.insert(SEC_WEBSOCKET_VERSION,
headers.insert(header::SEC_WEBSOCKET_VERSION,
header::HeaderValue::from_static("13"));
let req = HttpRequest::new(Method::GET, Uri::from_str("/").unwrap(),
Version::HTTP_11, headers, None);
@ -407,9 +402,9 @@ mod tests {
header::HeaderValue::from_static("websocket"));
headers.insert(header::CONNECTION,
header::HeaderValue::from_static("upgrade"));
headers.insert(SEC_WEBSOCKET_VERSION,
headers.insert(header::SEC_WEBSOCKET_VERSION,
header::HeaderValue::from_static("13"));
headers.insert(SEC_WEBSOCKET_KEY,
headers.insert(header::SEC_WEBSOCKET_KEY,
header::HeaderValue::from_static("13"));
let req = HttpRequest::new(Method::GET, Uri::from_str("/").unwrap(),
Version::HTTP_11, headers, None);