mirror of
https://github.com/fafhrd91/actix-web
synced 2024-12-18 01:43:58 +01:00
renamed Route::handler to Route::f, added Route::h to register Handler
This commit is contained in:
parent
03f7d95d88
commit
f5d6179a34
@ -108,8 +108,8 @@ fn main() {
|
|||||||
HttpServer::new(
|
HttpServer::new(
|
||||||
Application::default("/")
|
Application::default("/")
|
||||||
.middleware(middlewares::Logger::default()) // <- register logger middleware
|
.middleware(middlewares::Logger::default()) // <- register logger middleware
|
||||||
.resource("/ws/", |r| r.method(Method::GET)
|
.resource("/ws/", |r|
|
||||||
.handler(|req| ws::start(req, MyWebSocket))) // <- websocket route
|
r.method(Method::GET).f(|req| ws::start(req, MyWebSocket))) // <- websocket route
|
||||||
.route("/", fs::StaticFiles::new("examples/static/", true))) // <- serve static files
|
.route("/", fs::StaticFiles::new("examples/static/", true))) // <- serve static files
|
||||||
.serve::<_, ()>("127.0.0.1:8080").unwrap();
|
.serve::<_, ()>("127.0.0.1:8080").unwrap();
|
||||||
|
|
||||||
|
@ -69,11 +69,11 @@ fn main() {
|
|||||||
// register simple handle r, handle all methods
|
// register simple handle r, handle all methods
|
||||||
.handler("/index.html", index)
|
.handler("/index.html", index)
|
||||||
// with path parameters
|
// with path parameters
|
||||||
.resource("/user/{name}/", |r| r.route().method(Method::GET).handler(with_param))
|
.resource("/user/{name}/", |r| r.route().method(Method::GET).f(with_param))
|
||||||
// async handler
|
// async handler
|
||||||
.resource("/async/{name}", |r| r.route().method(Method::GET).async(index_async))
|
.resource("/async/{name}", |r| r.route().method(Method::GET).async(index_async))
|
||||||
// redirect
|
// redirect
|
||||||
.resource("/", |r| r.route().method(Method::GET).handler(|req| {
|
.resource("/", |r| r.route().method(Method::GET).f(|req| {
|
||||||
println!("{:?}", req);
|
println!("{:?}", req);
|
||||||
|
|
||||||
httpcodes::HTTPFound
|
httpcodes::HTTPFound
|
||||||
|
@ -65,8 +65,9 @@ fn main() {
|
|||||||
.middleware(middlewares::Logger::default())
|
.middleware(middlewares::Logger::default())
|
||||||
// websocket route
|
// websocket route
|
||||||
.resource(
|
.resource(
|
||||||
"/ws/", |r| r.route().method(Method::GET)
|
"/ws/", |r| r.route()
|
||||||
.handler(|req| ws::start(req, MyWebSocket{counter: 0})))
|
.method(Method::GET)
|
||||||
|
.f(|req| ws::start(req, MyWebSocket{counter: 0})))
|
||||||
// register simple handler, handle all methods
|
// register simple handler, handle all methods
|
||||||
.handler("/", index))
|
.handler("/", index))
|
||||||
.serve::<_, ()>("127.0.0.1:8080").unwrap();
|
.serve::<_, ()>("127.0.0.1:8080").unwrap();
|
||||||
|
@ -65,7 +65,7 @@ fn main() {
|
|||||||
// enable logger
|
// enable logger
|
||||||
.middleware(middlewares::Logger::default())
|
.middleware(middlewares::Logger::default())
|
||||||
// websocket route
|
// websocket route
|
||||||
.resource("/ws/", |r| r.route().method(Method::GET).handler(ws_index))
|
.resource("/ws/", |r| r.route().method(Method::GET).f(ws_index))
|
||||||
// static files
|
// static files
|
||||||
.route("/", fs::StaticFiles::new("examples/static/", true)))
|
.route("/", fs::StaticFiles::new("examples/static/", true)))
|
||||||
// start http server on 127.0.0.1:8080
|
// start http server on 127.0.0.1:8080
|
||||||
|
@ -77,8 +77,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).handler(|req| httpcodes::HTTPOk);
|
r.method(Method::GET).f(|req| httpcodes::HTTPOk);
|
||||||
r.method(Method::HEAD).handler(|req| httpcodes::HTTPMethodNotAllowed);
|
r.method(Method::HEAD).f(|req| httpcodes::HTTPMethodNotAllowed);
|
||||||
})
|
})
|
||||||
.finish();
|
.finish();
|
||||||
}
|
}
|
||||||
|
@ -2,7 +2,8 @@
|
|||||||
|
|
||||||
## Individual file
|
## Individual file
|
||||||
|
|
||||||
It is possible to serve static files with tail path pattern and `NamedFile`.
|
It is possible to serve static files with custom path pattern and `NamedFile`. To
|
||||||
|
match path tail we can use `.*` regex.
|
||||||
|
|
||||||
```rust
|
```rust
|
||||||
extern crate actix_web;
|
extern crate actix_web;
|
||||||
@ -16,7 +17,7 @@ fn index(req: HttpRequest) -> Result<fs::NamedFile> {
|
|||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
Application::default("/")
|
Application::default("/")
|
||||||
.resource(r"/a/{tail:*}", |r| r.method(Method::GET).handler(index))
|
.resource(r"/a/{tail:.*}", |r| r.method(Method::GET).f(index))
|
||||||
.finish();
|
.finish();
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
@ -49,7 +49,7 @@ request handler with the application's `resource` on a particular *HTTP method*
|
|||||||
# }
|
# }
|
||||||
# fn main() {
|
# fn main() {
|
||||||
let app = Application::default("/")
|
let app = Application::default("/")
|
||||||
.resource("/", |r| r.method(Method::GET).handler(index))
|
.resource("/", |r| r.method(Method::GET).f(index))
|
||||||
.finish();
|
.finish();
|
||||||
# }
|
# }
|
||||||
```
|
```
|
||||||
@ -80,7 +80,7 @@ fn main() {
|
|||||||
|
|
||||||
HttpServer::new(
|
HttpServer::new(
|
||||||
Application::default("/")
|
Application::default("/")
|
||||||
.resource("/", |r| r.route().handler(index)))
|
.resource("/", |r| r.route().f(index)))
|
||||||
.serve::<_, ()>("127.0.0.1:8088").unwrap();
|
.serve::<_, ()>("127.0.0.1:8088").unwrap();
|
||||||
|
|
||||||
println!("Started http server: 127.0.0.1:8088");
|
println!("Started http server: 127.0.0.1:8088");
|
||||||
|
@ -21,7 +21,7 @@ has same url path prefix:
|
|||||||
# }
|
# }
|
||||||
# fn main() {
|
# fn main() {
|
||||||
let app = Application::default("/prefix")
|
let app = Application::default("/prefix")
|
||||||
.resource("/index.html", |r| r.method(Method::GET).handler(index))
|
.resource("/index.html", |r| r.method(Method::GET).f(index))
|
||||||
.finish()
|
.finish()
|
||||||
# }
|
# }
|
||||||
```
|
```
|
||||||
@ -41,13 +41,13 @@ use tokio_core::net::TcpStream;
|
|||||||
fn main() {
|
fn main() {
|
||||||
HttpServer::<TcpStream, SocketAddr, _>::new(vec![
|
HttpServer::<TcpStream, SocketAddr, _>::new(vec![
|
||||||
Application::default("/app1")
|
Application::default("/app1")
|
||||||
.resource("/", |r| r.route().handler(|r| httpcodes::HTTPOk))
|
.resource("/", |r| r.route().f(|r| httpcodes::HTTPOk))
|
||||||
.finish(),
|
.finish(),
|
||||||
Application::default("/app2")
|
Application::default("/app2")
|
||||||
.resource("/", |r| r.route().handler(|r| httpcodes::HTTPOk))
|
.resource("/", |r| r.route().f(|r| httpcodes::HTTPOk))
|
||||||
.finish(),
|
.finish(),
|
||||||
Application::default("/")
|
Application::default("/")
|
||||||
.resource("/", |r| r.route().handler(|r| httpcodes::HTTPOk))
|
.resource("/", |r| r.route().f(|r| httpcodes::HTTPOk))
|
||||||
.finish(),
|
.finish(),
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
@ -79,7 +79,7 @@ fn main() {
|
|||||||
HttpServer::new(
|
HttpServer::new(
|
||||||
Application::default("/")
|
Application::default("/")
|
||||||
.resource("/", |r| r.method(
|
.resource("/", |r| r.method(
|
||||||
Method::GET).handler(|req| {MyObj{name: "user".to_owned()}})))
|
Method::GET).f(|req| {MyObj{name: "user".to_owned()}})))
|
||||||
.serve::<_, ()>("127.0.0.1:8088").unwrap();
|
.serve::<_, ()>("127.0.0.1:8088").unwrap();
|
||||||
|
|
||||||
println!("Started http server: 127.0.0.1:8088");
|
println!("Started http server: 127.0.0.1:8088");
|
||||||
|
@ -55,8 +55,8 @@ if no route could be matched default response `HTTPMethodNotAllowed` get resturn
|
|||||||
fn main() {
|
fn main() {
|
||||||
Application::default("/")
|
Application::default("/")
|
||||||
.resource("/prefix", |r| {
|
.resource("/prefix", |r| {
|
||||||
r.method(Method::GET).handler(|r| httpcodes::HTTPOk);
|
r.method(Method::GET).h(httpcodes::HTTPOk);
|
||||||
r.method(Method::POST).handler(|r| httpcodes::HTTPForbidden);
|
r.method(Method::POST).h(httpcodes::HTTPForbidden);
|
||||||
})
|
})
|
||||||
.finish();
|
.finish();
|
||||||
}
|
}
|
||||||
@ -87,7 +87,7 @@ fn index(req: HttpRequest) -> String {
|
|||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
Application::default("/")
|
Application::default("/")
|
||||||
.resource("/{name}", |r| r.method(Method::GET).handler(index))
|
.resource("/{name}", |r| r.method(Method::GET).f(index))
|
||||||
.finish();
|
.finish();
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
@ -105,7 +105,7 @@ You can also specify a custom regex in the form `{identifier:regex}`:
|
|||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
Application::default("/")
|
Application::default("/")
|
||||||
.resource(r"{name:\d+}", |r| r.method(Method::GET).handler(index))
|
.resource(r"{name:\d+}", |r| r.method(Method::GET).f(index))
|
||||||
.finish();
|
.finish();
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
@ -126,7 +126,7 @@ fn index(req: HttpRequest) -> Result<String> {
|
|||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
Application::default("/")
|
Application::default("/")
|
||||||
.resource(r"/a/{v1}/{v2}/", |r| r.route().handler(index))
|
.resource(r"/a/{v1}/{v2}/", |r| r.route().f(index))
|
||||||
.finish();
|
.finish();
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
@ -138,7 +138,7 @@ It is possible to match path tail with custom `.*` regex.
|
|||||||
```rust,ignore
|
```rust,ignore
|
||||||
fn main() {
|
fn main() {
|
||||||
Application::default("/")
|
Application::default("/")
|
||||||
.resource(r"/test/{tail:.*}", |r| r.method(Method::GET).handler(index))
|
.resource(r"/test/{tail:.*}", |r| r.method(Method::GET).f(index))
|
||||||
.finish();
|
.finish();
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
@ -174,7 +174,7 @@ fn index(req: HttpRequest) -> Result<String> {
|
|||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
Application::default("/")
|
Application::default("/")
|
||||||
.resource(r"/a/{tail:.*}", |r| r.method(Method::GET).handler(index))
|
.resource(r"/a/{tail:.*}", |r| r.method(Method::GET).f(index))
|
||||||
.finish();
|
.finish();
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
@ -30,7 +30,7 @@ fn index(req: HttpRequest<AppState>) -> String {
|
|||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
Application::build("/", AppState{counter: Cell::new(0)})
|
Application::build("/", AppState{counter: Cell::new(0)})
|
||||||
.resource("/", |r| r.method(Method::GET).handler(index))
|
.resource("/", |r| r.method(Method::GET).f(index))
|
||||||
.finish();
|
.finish();
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
@ -54,7 +54,7 @@ fn index(req: HttpRequest) -> Result<Json<MyObj>> {
|
|||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
Application::default("/")
|
Application::default("/")
|
||||||
.resource(r"/a/{name}", |r| r.method(Method::GET).handler(index))
|
.resource(r"/a/{name}", |r| r.method(Method::GET).f(index))
|
||||||
.finish();
|
.finish();
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
@ -134,8 +134,8 @@ impl<S> ApplicationBuilder<S> where S: 'static {
|
|||||||
/// fn main() {
|
/// fn main() {
|
||||||
/// let app = Application::default("/")
|
/// let app = Application::default("/")
|
||||||
/// .resource("/test", |r| {
|
/// .resource("/test", |r| {
|
||||||
/// r.method(Method::GET).handler(|_| httpcodes::HTTPOk);
|
/// r.method(Method::GET).f(|_| httpcodes::HTTPOk);
|
||||||
/// r.method(Method::HEAD).handler(|_| httpcodes::HTTPMethodNotAllowed);
|
/// r.method(Method::HEAD).f(|_| httpcodes::HTTPMethodNotAllowed);
|
||||||
/// })
|
/// })
|
||||||
/// .finish();
|
/// .finish();
|
||||||
/// }
|
/// }
|
||||||
|
@ -3,7 +3,7 @@
|
|||||||
use http::{StatusCode, Error as HttpError};
|
use http::{StatusCode, Error as HttpError};
|
||||||
|
|
||||||
use body::Body;
|
use body::Body;
|
||||||
use route::{Reply, RouteHandler, FromRequest};
|
use route::{Reply, Handler, RouteHandler, FromRequest};
|
||||||
use httprequest::HttpRequest;
|
use httprequest::HttpRequest;
|
||||||
use httpresponse::{HttpResponse, HttpResponseBuilder};
|
use httpresponse::{HttpResponse, HttpResponseBuilder};
|
||||||
|
|
||||||
@ -67,6 +67,14 @@ impl StaticResponse {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl<S> Handler<S> for StaticResponse {
|
||||||
|
type Result = HttpResponse;
|
||||||
|
|
||||||
|
fn handle(&self, _: HttpRequest<S>) -> HttpResponse {
|
||||||
|
HttpResponse::new(self.0, Body::Empty)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl<S> RouteHandler<S> for StaticResponse {
|
impl<S> RouteHandler<S> for StaticResponse {
|
||||||
fn handle(&self, _: HttpRequest<S>) -> Reply {
|
fn handle(&self, _: HttpRequest<S>) -> Reply {
|
||||||
Reply::response(HttpResponse::new(self.0, Body::Empty))
|
Reply::response(HttpResponse::new(self.0, Body::Empty))
|
||||||
|
@ -21,8 +21,8 @@ use middlewares::{Response, Middleware};
|
|||||||
/// .header("X-Version", "0.2")
|
/// .header("X-Version", "0.2")
|
||||||
/// .finish())
|
/// .finish())
|
||||||
/// .resource("/test", |r| {
|
/// .resource("/test", |r| {
|
||||||
/// r.method(Method::GET).handler(|_| httpcodes::HTTPOk);
|
/// r.method(Method::GET).f(|_| httpcodes::HTTPOk);
|
||||||
/// r.method(Method::HEAD).handler(|_| httpcodes::HTTPMethodNotAllowed);
|
/// r.method(Method::HEAD).f(|_| httpcodes::HTTPMethodNotAllowed);
|
||||||
/// })
|
/// })
|
||||||
/// .finish();
|
/// .finish();
|
||||||
/// }
|
/// }
|
||||||
|
@ -10,7 +10,10 @@ use httpcodes::HTTPNotFound;
|
|||||||
use httprequest::HttpRequest;
|
use httprequest::HttpRequest;
|
||||||
use httpresponse::HttpResponse;
|
use httpresponse::HttpResponse;
|
||||||
|
|
||||||
/// Resource route definition. Route uses builder-like pattern for configuration.
|
/// Resource route definition
|
||||||
|
///
|
||||||
|
/// Route uses builder-like pattern for configuration.
|
||||||
|
/// If handler is not explicitly set, default *404 Not Found* handler is used.
|
||||||
pub struct Route<S> {
|
pub struct Route<S> {
|
||||||
preds: Vec<Box<Predicate<S>>>,
|
preds: Vec<Box<Predicate<S>>>,
|
||||||
handler: Box<RouteHandler<S>>,
|
handler: Box<RouteHandler<S>>,
|
||||||
@ -55,16 +58,21 @@ impl<S: 'static> Route<S> {
|
|||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/// Add method check to route. This method could be called multiple times.
|
/// Add method check to route. This method could be called multiple times.
|
||||||
pub fn method(&mut self, method: Method) -> &mut Self {
|
pub fn method(&mut self, method: Method) -> &mut Self {
|
||||||
self.preds.push(pred::Method(method));
|
self.preds.push(pred::Method(method));
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 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) {
|
||||||
|
self.handler = Box::new(WrapHandler::new(handler));
|
||||||
|
}
|
||||||
|
|
||||||
/// Set handler function. Usually call to this method is last call
|
/// Set handler function. Usually call to this method is last call
|
||||||
/// during route configuration, because it does not return reference to self.
|
/// during route configuration, because it does not return reference to self.
|
||||||
pub fn handler<F, R>(&mut self, handler: F)
|
pub fn f<F, R>(&mut self, handler: F)
|
||||||
where F: Fn(HttpRequest<S>) -> R + 'static,
|
where F: Fn(HttpRequest<S>) -> R + 'static,
|
||||||
R: FromRequest + 'static,
|
R: FromRequest + 'static,
|
||||||
{
|
{
|
||||||
@ -99,7 +107,7 @@ impl<S: 'static> Route<S> {
|
|||||||
/// fn main() {
|
/// fn main() {
|
||||||
/// let app = Application::default("/")
|
/// let app = Application::default("/")
|
||||||
/// .resource(
|
/// .resource(
|
||||||
/// "/", |r| r.route().method(Method::GET).handler(|r| HttpResponse::Ok()))
|
/// "/", |r| r.route().method(Method::GET).f(|r| HttpResponse::Ok()))
|
||||||
/// .finish();
|
/// .finish();
|
||||||
/// }
|
/// }
|
||||||
pub struct Resource<S=()> {
|
pub struct Resource<S=()> {
|
||||||
@ -147,7 +155,7 @@ impl<S> Resource<S> where S: 'static {
|
|||||||
/// "/", |r| r.route()
|
/// "/", |r| r.route()
|
||||||
/// .p(pred::Any(vec![pred::Get(), pred::Put()]))
|
/// .p(pred::Any(vec![pred::Get(), pred::Put()]))
|
||||||
/// .p(pred::Header("Content-Type", "text/plain"))
|
/// .p(pred::Header("Content-Type", "text/plain"))
|
||||||
/// .handler(|r| HttpResponse::Ok()))
|
/// .f(|r| HttpResponse::Ok()))
|
||||||
/// .finish();
|
/// .finish();
|
||||||
/// }
|
/// }
|
||||||
pub fn route(&mut self) -> &mut Route<S> {
|
pub fn route(&mut self) -> &mut Route<S> {
|
||||||
|
21
src/route.rs
21
src/route.rs
@ -227,6 +227,27 @@ impl<S, R, F> RouteHandler<S> for AsyncHandler<S, R, F>
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// Json response helper
|
||||||
|
///
|
||||||
|
/// The `Json` type allows you to respond with well-formed JSON data: simply return a value of
|
||||||
|
/// type Json<T> where T is the type of a structure to serialize into *JSON*. The
|
||||||
|
/// type `T` must implement the `Serialize` trait from *serde*.
|
||||||
|
///
|
||||||
|
/// ```rust
|
||||||
|
/// # extern crate actix_web;
|
||||||
|
/// # #[macro_use] extern crate serde_derive;
|
||||||
|
/// # use actix_web::*;
|
||||||
|
/// #
|
||||||
|
/// #[derive(Serialize)]
|
||||||
|
/// struct MyObj {
|
||||||
|
/// name: String,
|
||||||
|
/// }
|
||||||
|
///
|
||||||
|
/// fn index(req: HttpRequest) -> Result<Json<MyObj>> {
|
||||||
|
/// Ok(Json(MyObj{name: req.match_info().query("name")?}))
|
||||||
|
/// }
|
||||||
|
/// # fn main() {}
|
||||||
|
/// ```
|
||||||
pub struct Json<T: Serialize> (pub T);
|
pub struct Json<T: Serialize> (pub T);
|
||||||
|
|
||||||
impl<T: Serialize> FromRequest for Json<T> {
|
impl<T: Serialize> FromRequest for Json<T> {
|
||||||
|
@ -43,7 +43,7 @@
|
|||||||
//!
|
//!
|
||||||
//! fn main() {
|
//! fn main() {
|
||||||
//! Application::default("/")
|
//! Application::default("/")
|
||||||
//! .resource("/ws/", |r| r.method(Method::GET).handler(ws_index)) // <- register websocket route
|
//! .resource("/ws/", |r| r.method(Method::GET).f(ws_index)) // <- register websocket route
|
||||||
//! .finish();
|
//! .finish();
|
||||||
//! }
|
//! }
|
||||||
//! ```
|
//! ```
|
||||||
|
@ -16,7 +16,7 @@ fn create_server<T, A>() -> HttpServer<T, A, Application<()>> {
|
|||||||
HttpServer::new(
|
HttpServer::new(
|
||||||
vec![Application::default("/")
|
vec![Application::default("/")
|
||||||
.resource("/", |r|
|
.resource("/", |r|
|
||||||
r.route().method(Method::GET).handler(|_| httpcodes::HTTPOk))
|
r.route().method(Method::GET).h(httpcodes::HTTPOk))
|
||||||
.finish()])
|
.finish()])
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -94,7 +94,7 @@ fn test_middlewares() {
|
|||||||
response: act_num2,
|
response: act_num2,
|
||||||
finish: act_num3})
|
finish: act_num3})
|
||||||
.resource("/", |r|
|
.resource("/", |r|
|
||||||
r.route().method(Method::GET).handler(|_| httpcodes::HTTPOk))
|
r.route().method(Method::GET).h(httpcodes::HTTPOk))
|
||||||
.finish()])
|
.finish()])
|
||||||
.serve::<_, ()>("127.0.0.1:58904").unwrap();
|
.serve::<_, ()>("127.0.0.1:58904").unwrap();
|
||||||
sys.run();
|
sys.run();
|
||||||
|
Loading…
Reference in New Issue
Block a user