1
0
Fork 0
mirror of https://github.com/actix/actix-web.git synced 2024-11-25 19:11:10 +00:00

better handler function ergonimics

This commit is contained in:
Nikolay Kim 2017-10-29 21:39:59 -07:00
parent 8aa20c6261
commit 4e216701c0
6 changed files with 25 additions and 15 deletions

View file

@ -12,13 +12,14 @@ fn index(req: &mut HttpRequest, _payload: Payload, state: &()) -> HttpResponse {
} }
/// handle with path parameters like `/name/{name}/` /// handle with path parameters like `/name/{name}/`
fn with_param(req: &mut HttpRequest, _payload: Payload, state: &()) -> HttpResponse { fn with_param(req: &mut HttpRequest, _payload: Payload, state: &())
-> HandlerResult<HttpResponse>
{
println!("{:?}", req); println!("{:?}", req);
HttpResponse::builder(StatusCode::OK) Ok(HttpResponse::builder(StatusCode::OK)
.content_type("test/plain") .content_type("test/plain")
.body(format!("Hello {}!", req.match_info().get("name").unwrap())) .body(format!("Hello {}!", req.match_info().get("name").unwrap()))?)
.unwrap()
} }
fn main() { fn main() {
@ -38,10 +39,10 @@ fn main() {
.resource("/", |r| r.handler(Method::GET, |req, _, _| { .resource("/", |r| r.handler(Method::GET, |req, _, _| {
println!("{:?}", req); println!("{:?}", req);
httpcodes::HTTPFound Ok(httpcodes::HTTPFound
.builder() .builder()
.header("LOCATION", "/index.html") .header("LOCATION", "/index.html")
.body(Body::Empty) .body(Body::Empty)?)
})) }))
// static files // static files
.route_handler("/static", StaticFiles::new("examples/static/", true))) .route_handler("/static", StaticFiles::new("examples/static/", true)))

View file

@ -180,7 +180,7 @@ impl<S> ApplicationBuilder<S> where S: 'static {
/// .resource("/test", |r| { /// .resource("/test", |r| {
/// r.get::<MyRoute>(); /// r.get::<MyRoute>();
/// r.handler(Method::HEAD, |req, payload, state| { /// r.handler(Method::HEAD, |req, payload, state| {
/// httpcodes::HTTPMethodNotAllowed /// Ok(httpcodes::HTTPMethodNotAllowed)
/// }); /// });
/// }) /// })
/// .finish(); /// .finish();

View file

@ -123,6 +123,13 @@ impl From<HttpError> for HttpResponse {
} }
} }
/// Return `InternalServerError` for `io::Error`
impl From<IoError> for HttpResponse {
fn from(err: IoError) -> Self {
HttpResponse::from_error(StatusCode::INTERNAL_SERVER_ERROR, err)
}
}
/// Return `BadRequest` for `cookie::ParseError` /// Return `BadRequest` for `cookie::ParseError`
impl From<cookie::ParseError> for HttpResponse { impl From<cookie::ParseError> for HttpResponse {
fn from(err: cookie::ParseError) -> Self { fn from(err: cookie::ParseError) -> Self {

View file

@ -52,7 +52,7 @@ pub use httprequest::{HttpRequest, UrlEncoded};
pub use httpresponse::{HttpResponse, HttpResponseBuilder}; pub use httpresponse::{HttpResponse, HttpResponseBuilder};
pub use payload::{Payload, PayloadItem, PayloadError}; pub use payload::{Payload, PayloadItem, PayloadError};
pub use route::{Route, RouteFactory, RouteHandler, RouteResult}; pub use route::{Route, RouteFactory, RouteHandler, RouteResult};
pub use resource::{Reply, Resource}; pub use resource::{Reply, Resource, HandlerResult};
pub use recognizer::{Params, RouteRecognizer}; pub use recognizer::{Params, RouteRecognizer};
pub use logger::Logger; pub use logger::Logger;
pub use server::HttpServer; pub use server::HttpServer;

View file

@ -15,6 +15,9 @@ use httprequest::HttpRequest;
use httpresponse::HttpResponse; use httpresponse::HttpResponse;
use httpcodes::{HTTPNotFound, HTTPMethodNotAllowed}; use httpcodes::{HTTPNotFound, HTTPMethodNotAllowed};
/// Result of a resource handler function
pub type HandlerResult<T> = Result<T, HttpResponse>;
/// Http resource /// Http resource
/// ///
/// `Resource` is an entry in route table which corresponds to requested URL. /// `Resource` is an entry in route table which corresponds to requested URL.
@ -48,7 +51,6 @@ impl<S> Default for Resource<S> {
} }
} }
impl<S> Resource<S> where S: 'static { impl<S> Resource<S> where S: 'static {
pub(crate) fn default_not_found() -> Self { pub(crate) fn default_not_found() -> Self {
@ -66,7 +68,7 @@ impl<S> Resource<S> where S: 'static {
/// Register handler for specified method. /// Register handler for specified method.
pub fn handler<F, R>(&mut self, method: Method, handler: F) pub fn handler<F, R>(&mut self, method: Method, handler: F)
where F: Fn(&mut HttpRequest, Payload, &S) -> R + 'static, where F: Fn(&mut HttpRequest, Payload, &S) -> HandlerResult<R> + 'static,
R: Into<HttpResponse> + 'static, R: Into<HttpResponse> + 'static,
{ {
self.routes.insert(method, Box::new(FnHandler::new(handler))); self.routes.insert(method, Box::new(FnHandler::new(handler)));

View file

@ -16,7 +16,7 @@ fn create_server<T, A>() -> HttpServer<T, A, Application<()>> {
vec![Application::default("/") vec![Application::default("/")
.resource("/", |r| .resource("/", |r|
r.handler(Method::GET, |_, _, _| { r.handler(Method::GET, |_, _, _| {
httpcodes::HTTPOk Ok(httpcodes::HTTPOk)
})) }))
.finish()]) .finish()])
} }
@ -96,7 +96,7 @@ fn test_middlewares() {
finish: act_num3}) finish: act_num3})
.resource("/", |r| .resource("/", |r|
r.handler(Method::GET, |_, _, _| { r.handler(Method::GET, |_, _, _| {
httpcodes::HTTPOk Ok(httpcodes::HTTPOk)
})) }))
.finish()]) .finish()])
.serve::<_, ()>("127.0.0.1:58904").unwrap(); .serve::<_, ()>("127.0.0.1:58904").unwrap();