Skip to content

Default Handler Implementation #64

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Nov 28, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions examples/default_handler.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
#![feature(async_await)]

use http::status::StatusCode;
use tide::body;

fn main() {
let mut app = tide::App::new(());
app.at("/").get(async || "Hello, world!");

app.default_handler(async || {
http::Response::builder()
.status(StatusCode::NOT_FOUND)
.header("Content-Type", "text/plain")
.body(body::Body::from("¯\\_(ツ)_/¯".to_string().into_bytes()))
.unwrap()
});

let address = "127.0.0.1:8000".to_owned();
println!("Server is listening on http://{}", address);
app.serve(address)
}
46 changes: 27 additions & 19 deletions src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ use std::{

use crate::{
body::Body,
endpoint::BoxedEndpoint,
endpoint::Endpoint,
extract::Extract,
middleware::{logger::RootLogger, RequestContext},
router::{Resource, RouteResult, Router},
Expand All @@ -25,6 +27,7 @@ use crate::{
pub struct App<Data> {
data: Data,
router: Router<Data>,
default_handler: BoxedEndpoint<Data>,
}

impl<Data: Clone + Send + Sync + 'static> App<Data> {
Expand All @@ -34,6 +37,7 @@ impl<Data: Clone + Send + Sync + 'static> App<Data> {
let mut app = App {
data,
router: Router::new(),
default_handler: BoxedEndpoint::new(async || http::status::StatusCode::NOT_FOUND),
};

// Add RootLogger as a default middleware
Expand All @@ -52,6 +56,12 @@ impl<Data: Clone + Send + Sync + 'static> App<Data> {
self.router.at(path)
}

/// Set the default handler for the app, a fallback function when there is no match to the route requested
pub fn default_handler<T: Endpoint<Data, U>, U>(&mut self, handler: T) -> &mut Self {
self.default_handler = BoxedEndpoint::new(handler);
self
}

/// Apply `middleware` to the whole app. Note that the order of nesting subrouters and applying
/// middleware matters; see `Router` for details.
pub fn middleware(&mut self, middleware: impl Middleware<Data> + 'static) -> &mut Self {
Expand All @@ -63,6 +73,7 @@ impl<Data: Clone + Send + Sync + 'static> App<Data> {
Server {
data: self.data,
router: Arc::new(self.router),
default_handler: Arc::new(self.default_handler),
}
}

Expand Down Expand Up @@ -94,6 +105,7 @@ impl<Data: Clone + Send + Sync + 'static> App<Data> {
struct Server<Data> {
data: Data,
router: Arc<Router<Data>>,
default_handler: Arc<BoxedEndpoint<Data>>,
}

impl<Data: Clone + Send + Sync + 'static> Service for Server<Data> {
Expand All @@ -105,34 +117,30 @@ impl<Data: Clone + Send + Sync + 'static> Service for Server<Data> {
fn call(&mut self, req: http::Request<hyper::Body>) -> Self::Future {
let data = self.data.clone();
let router = self.router.clone();
let default_handler = self.default_handler.clone();

let req = req.map(Body::from);
let path = req.uri().path().to_owned();
let method = req.method().to_owned();

FutureObj::new(Box::new(
async move {
if let Some(RouteResult {
let RouteResult {
endpoint,
params,
middleware,
}) = router.route(&path, &method)
{
let ctx = RequestContext {
app_data: data,
req,
params,
endpoint,
next_middleware: middleware,
};
let res = await!(ctx.next());
Ok(res.map(Into::into))
} else {
Ok(http::Response::builder()
.status(http::status::StatusCode::NOT_FOUND)
.body(hyper::Body::empty())
.unwrap())
}
} = router.route(&path, &method, &default_handler);

let ctx = RequestContext {
app_data: data,
req,
params,
endpoint,
next_middleware: middleware,
};
let res = await!(ctx.next());

Ok(res.map(Into::into))
},
))
.compat()
Expand All @@ -158,7 +166,7 @@ impl<T> DerefMut for AppData<T> {

impl<T: Clone + Send + 'static> Extract<T> for AppData<T> {
type Fut = future::Ready<Result<Self, Response>>;
fn extract(data: &mut T, req: &mut Request, params: &RouteMatch<'_>) -> Self::Fut {
fn extract(data: &mut T, req: &mut Request, params: &Option<RouteMatch<'_>>) -> Self::Fut {
future::ok(AppData(data.clone()))
}
}
14 changes: 8 additions & 6 deletions src/body.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ use crate::{Extract, IntoResponse, Request, Response, RouteMatch};
/// A body is a stream of `BodyChunk`s, which are essentially `Vec<u8>` values.
/// Both `Body` and `BodyChunk` values can be easily created from standard byte buffer types,
/// using the `From` trait.
#[derive(Debug)]
pub struct Body {
inner: BodyInner,
}
Expand All @@ -43,6 +44,7 @@ impl From<String> for BodyChunk {
}
}

#[derive(Debug)]
enum BodyInner {
Streaming(BodyStream),
Fixed(Vec<u8>),
Expand Down Expand Up @@ -130,7 +132,7 @@ impl<S: 'static> Extract<S> for MultipartForm {
// Note: cannot use `existential type` here due to ICE
type Fut = FutureObj<'static, Result<Self, Response>>;

fn extract(data: &mut S, req: &mut Request, params: &RouteMatch<'_>) -> Self::Fut {
fn extract(data: &mut S, req: &mut Request, params: &Option<RouteMatch<'_>>) -> Self::Fut {
// https://stackoverflow.com/questions/43424982/how-to-parse-multipart-forms-using-abonander-multipart-with-rocket

const BOUNDARY: &str = "boundary=";
Expand Down Expand Up @@ -176,7 +178,7 @@ impl<T: Send + serde::de::DeserializeOwned + 'static, S: 'static> Extract<S> for
// Note: cannot use `existential type` here due to ICE
type Fut = FutureObj<'static, Result<Self, Response>>;

fn extract(data: &mut S, req: &mut Request, params: &RouteMatch<'_>) -> Self::Fut {
fn extract(data: &mut S, req: &mut Request, params: &Option<RouteMatch<'_>>) -> Self::Fut {
let mut body = std::mem::replace(req.body_mut(), Body::empty());
FutureObj::new(Box::new(
async move {
Expand Down Expand Up @@ -223,7 +225,7 @@ impl<T: Send + serde::de::DeserializeOwned + 'static, S: 'static> Extract<S> for
// Note: cannot use `existential type` here due to ICE
type Fut = FutureObj<'static, Result<Self, Response>>;

fn extract(data: &mut S, req: &mut Request, params: &RouteMatch<'_>) -> Self::Fut {
fn extract(data: &mut S, req: &mut Request, params: &Option<RouteMatch<'_>>) -> Self::Fut {
let mut body = std::mem::replace(req.body_mut(), Body::empty());
FutureObj::new(Box::new(
async move {
Expand Down Expand Up @@ -266,7 +268,7 @@ pub struct Str(pub String);
impl<S: 'static> Extract<S> for Str {
type Fut = FutureObj<'static, Result<Self, Response>>;

fn extract(data: &mut S, req: &mut Request, params: &RouteMatch<'_>) -> Self::Fut {
fn extract(data: &mut S, req: &mut Request, params: &Option<RouteMatch<'_>>) -> Self::Fut {
let mut body = std::mem::replace(req.body_mut(), Body::empty());

FutureObj::new(Box::new(
Expand Down Expand Up @@ -297,7 +299,7 @@ pub struct StrLossy(pub String);
impl<S: 'static> Extract<S> for StrLossy {
type Fut = FutureObj<'static, Result<Self, Response>>;

fn extract(data: &mut S, req: &mut Request, params: &RouteMatch<'_>) -> Self::Fut {
fn extract(data: &mut S, req: &mut Request, params: &Option<RouteMatch<'_>>) -> Self::Fut {
let mut body = std::mem::replace(req.body_mut(), Body::empty());

FutureObj::new(Box::new(
Expand Down Expand Up @@ -328,7 +330,7 @@ pub struct Bytes(pub Vec<u8>);
impl<S: 'static> Extract<S> for Bytes {
type Fut = FutureObj<'static, Result<Self, Response>>;

fn extract(data: &mut S, req: &mut Request, params: &RouteMatch<'_>) -> Self::Fut {
fn extract(data: &mut S, req: &mut Request, params: &Option<RouteMatch<'_>>) -> Self::Fut {
let mut body = std::mem::replace(req.body_mut(), Body::empty());

FutureObj::new(Box::new(
Expand Down
8 changes: 4 additions & 4 deletions src/endpoint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,11 @@ pub trait Endpoint<Data, Kind>: Send + Sync + 'static {
type Fut: Future<Output = Response> + Send + 'static;

/// Invoke the endpoint on the given request and app data handle.
fn call(&self, data: Data, req: Request, params: RouteMatch<'_>) -> Self::Fut;
fn call(&self, data: Data, req: Request, params: Option<RouteMatch<'_>>) -> Self::Fut;
}

type BoxedEndpointFn<Data> =
dyn Fn(Data, Request, RouteMatch) -> FutureObj<'static, Response> + Send + Sync;
dyn Fn(Data, Request, Option<RouteMatch>) -> FutureObj<'static, Response> + Send + Sync;

pub(crate) struct BoxedEndpoint<Data> {
endpoint: Box<BoxedEndpointFn<Data>>,
Expand All @@ -37,7 +37,7 @@ impl<Data> BoxedEndpoint<Data> {
&self,
data: Data,
req: Request,
params: RouteMatch<'_>,
params: Option<RouteMatch<'_>>,
) -> FutureObj<'static, Response> {
(self.endpoint)(data, req, params)
}
Expand Down Expand Up @@ -71,7 +71,7 @@ macro_rules! end_point_impl_raw {
type Fut = FutureObj<'static, Response>;

#[allow(unused_mut, non_snake_case)]
fn call(&self, mut data: Data, mut req: Request, params: RouteMatch<'_>) -> Self::Fut {
fn call(&self, mut data: Data, mut req: Request, params: Option<RouteMatch<'_>>) -> Self::Fut {
let f = self.clone();
$(let $X = $X::extract(&mut data, &mut req, &params);)*
FutureObj::new(Box::new(async move {
Expand Down
2 changes: 1 addition & 1 deletion src/extract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,5 @@ pub trait Extract<Data>: Send + Sized + 'static {
type Fut: Future<Output = Result<Self, Response>> + Send + 'static;

/// Attempt to extract a value from the given request.
fn extract(data: &mut Data, req: &mut Request, params: &RouteMatch<'_>) -> Self::Fut;
fn extract(data: &mut Data, req: &mut Request, params: &Option<RouteMatch<'_>>) -> Self::Fut;
}
34 changes: 20 additions & 14 deletions src/head.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,12 +77,15 @@ struct PathIdx(usize);

impl<T: Send + 'static + std::str::FromStr, S: 'static> Extract<S> for Path<T> {
type Fut = future::Ready<Result<Self, Response>>;
fn extract(data: &mut S, req: &mut Request, params: &RouteMatch<'_>) -> Self::Fut {
fn extract(data: &mut S, req: &mut Request, params: &Option<RouteMatch<'_>>) -> Self::Fut {
let &PathIdx(i) = req.extensions().get::<PathIdx>().unwrap_or(&PathIdx(0));
req.extensions_mut().insert(PathIdx(i + 1));
match params.vec[i].parse() {
Ok(t) => future::ok(Path(t)),
Err(_) => future::err(http::status::StatusCode::BAD_REQUEST.into_response()),
match params {
Some(params) => match params.vec[i].parse() {
Ok(t) => future::ok(Path(t)),
Err(_) => future::err(http::status::StatusCode::BAD_REQUEST.into_response()),
},
None => future::err(http::status::StatusCode::INTERNAL_SERVER_ERROR.into_response()),
}
}
}
Expand Down Expand Up @@ -116,15 +119,18 @@ impl<T: NamedComponent> DerefMut for Named<T> {
impl<T: NamedComponent, S: 'static> Extract<S> for Named<T> {
type Fut = future::Ready<Result<Self, Response>>;

fn extract(data: &mut S, req: &mut Request, params: &RouteMatch<'_>) -> Self::Fut {
params
.map
.get(T::NAME)
.and_then(|component| component.parse().ok())
.map_or(
future::err(http::status::StatusCode::BAD_REQUEST.into_response()),
|t| future::ok(Named(t)),
)
fn extract(data: &mut S, req: &mut Request, params: &Option<RouteMatch<'_>>) -> Self::Fut {
match params {
Some(params) => params
.map
.get(T::NAME)
.and_then(|component| component.parse().ok())
.map_or(
future::err(http::status::StatusCode::BAD_REQUEST.into_response()),
|t| future::ok(Named(t)),
),
None => future::err(http::status::StatusCode::BAD_REQUEST.into_response()),
}
}
}

Expand All @@ -138,7 +144,7 @@ where
S: 'static,
{
type Fut = future::Ready<Result<Self, Response>>;
fn extract(data: &mut S, req: &mut Request, params: &RouteMatch<'_>) -> Self::Fut {
fn extract(data: &mut S, req: &mut Request, params: &Option<RouteMatch<'_>>) -> Self::Fut {
req.uri().query().and_then(|q| q.parse().ok()).map_or(
future::err(http::status::StatusCode::BAD_REQUEST.into_response()),
|q| future::ok(UrlQuery(q)),
Expand Down
2 changes: 1 addition & 1 deletion src/middleware/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ where
pub struct RequestContext<'a, Data> {
pub app_data: Data,
pub req: Request,
pub params: RouteMatch<'a>,
pub params: Option<RouteMatch<'a>>,
pub(crate) endpoint: &'a BoxedEndpoint<Data>,
pub(crate) next_middleware: &'a [Arc<dyn Middleware<Data> + Send + Sync>],
}
Expand Down
2 changes: 1 addition & 1 deletion src/request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ impl<T> DerefMut for Computed<T> {

impl<Data: 'static, T: Compute> Extract<Data> for Computed<T> {
type Fut = future::Ready<Result<Self, Response>>;
fn extract(data: &mut Data, req: &mut Request, params: &RouteMatch<'_>) -> Self::Fut {
fn extract(data: &mut Data, req: &mut Request, params: &Option<RouteMatch<'_>>) -> Self::Fut {
future::ok(Computed(T::compute(req)))
}
}
Loading