1
0
Fork 0
mirror of https://github.com/actix/actix-web.git synced 2024-06-12 10:19:36 +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}/`
fn with_param(req: &mut HttpRequest, _payload: Payload, state: &()) -> HttpResponse {
fn with_param(req: &mut HttpRequest, _payload: Payload, state: &())
-> HandlerResult<HttpResponse>
{
println!("{:?}", req);
HttpResponse::builder(StatusCode::OK)
.content_type("test/plain")
.body(format!("Hello {}!", req.match_info().get("name").unwrap()))
.unwrap()
Ok(HttpResponse::builder(StatusCode::OK)
.content_type("test/plain")
.body(format!("Hello {}!", req.match_info().get("name").unwrap()))?)
}
fn main() {
@ -38,10 +39,10 @@ fn main() {
.resource("/", |r| r.handler(Method::GET, |req, _, _| {
println!("{:?}", req);
httpcodes::HTTPFound
.builder()
.header("LOCATION", "/index.html")
.body(Body::Empty)
Ok(httpcodes::HTTPFound
.builder()
.header("LOCATION", "/index.html")
.body(Body::Empty)?)
}))
// static files
.route_handler("/static", StaticFiles::new("examples/static/", true)))

View file

@ -180,7 +180,7 @@ impl<S> ApplicationBuilder<S> where S: 'static {
/// .resource("/test", |r| {
/// r.get::<MyRoute>();
/// r.handler(Method::HEAD, |req, payload, state| {
/// httpcodes::HTTPMethodNotAllowed
/// Ok(httpcodes::HTTPMethodNotAllowed)
/// });
/// })
/// .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`
impl From<cookie::ParseError> for HttpResponse {
fn from(err: cookie::ParseError) -> Self {

View file

@ -52,7 +52,7 @@ pub use httprequest::{HttpRequest, UrlEncoded};
pub use httpresponse::{HttpResponse, HttpResponseBuilder};
pub use payload::{Payload, PayloadItem, PayloadError};
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 logger::Logger;
pub use server::HttpServer;

View file

@ -15,6 +15,9 @@ use httprequest::HttpRequest;
use httpresponse::HttpResponse;
use httpcodes::{HTTPNotFound, HTTPMethodNotAllowed};
/// Result of a resource handler function
pub type HandlerResult<T> = Result<T, HttpResponse>;
/// Http resource
///
/// `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 {
pub(crate) fn default_not_found() -> Self {
@ -66,7 +68,7 @@ impl<S> Resource<S> where S: 'static {
/// Register handler for specified method.
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,
{
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("/")
.resource("/", |r|
r.handler(Method::GET, |_, _, _| {
httpcodes::HTTPOk
Ok(httpcodes::HTTPOk)
}))
.finish()])
}
@ -96,7 +96,7 @@ fn test_middlewares() {
finish: act_num3})
.resource("/", |r|
r.handler(Method::GET, |_, _, _| {
httpcodes::HTTPOk
Ok(httpcodes::HTTPOk)
}))
.finish()])
.serve::<_, ()>("127.0.0.1:58904").unwrap();