2017-10-07 06:48:14 +02:00
|
|
|
use std::marker::PhantomData;
|
|
|
|
|
2017-12-09 20:39:13 +01:00
|
|
|
use regex::Regex;
|
2018-01-01 02:26:32 +01:00
|
|
|
use futures::future::{Future, ok, err};
|
2017-12-09 20:39:13 +01:00
|
|
|
use http::{header, StatusCode, Error as HttpError};
|
2017-10-07 06:48:14 +02:00
|
|
|
|
2017-12-09 20:39:13 +01:00
|
|
|
use body::Body;
|
2017-11-29 22:26:55 +01:00
|
|
|
use error::Error;
|
2017-10-15 07:52:38 +02:00
|
|
|
use httprequest::HttpRequest;
|
2017-10-24 08:25:32 +02:00
|
|
|
use httpresponse::HttpResponse;
|
2017-11-03 21:35:34 +01:00
|
|
|
|
2018-01-15 22:47:25 +01:00
|
|
|
/// Trait defines object that could be registered as route handler
|
2017-10-16 10:19:23 +02:00
|
|
|
#[allow(unused_variables)]
|
2017-11-29 22:26:55 +01:00
|
|
|
pub trait Handler<S>: 'static {
|
2017-11-30 00:07:49 +01:00
|
|
|
|
|
|
|
/// The type of value that handler will return.
|
2017-12-14 18:43:42 +01:00
|
|
|
type Result: Responder;
|
2017-11-29 22:26:55 +01:00
|
|
|
|
2017-10-10 08:07:32 +02:00
|
|
|
/// Handle request
|
2017-12-26 18:00:45 +01:00
|
|
|
fn handle(&mut self, req: HttpRequest<S>) -> Self::Result;
|
2017-10-07 06:48:14 +02:00
|
|
|
}
|
|
|
|
|
2017-12-14 18:43:42 +01:00
|
|
|
/// Trait implemented by types that generate responses for clients.
|
|
|
|
///
|
|
|
|
/// Types that implement this trait can be used as the return type of a handler.
|
|
|
|
pub trait Responder {
|
2017-12-03 23:22:04 +01:00
|
|
|
/// The associated item which can be returned.
|
|
|
|
type Item: Into<Reply>;
|
|
|
|
|
|
|
|
/// The associated error which can be returned.
|
|
|
|
type Error: Into<Error>;
|
|
|
|
|
2017-12-14 18:43:42 +01:00
|
|
|
/// Convert itself to `Reply` or `Error`.
|
|
|
|
fn respond_to(self, req: HttpRequest) -> Result<Self::Item, Self::Error>;
|
2017-12-03 01:37:21 +01:00
|
|
|
}
|
|
|
|
|
2018-03-11 17:36:54 +01:00
|
|
|
/// Combines two different responder types into a single type
|
2018-03-10 19:12:44 +01:00
|
|
|
///
|
|
|
|
/// ```rust
|
|
|
|
/// # extern crate actix_web;
|
|
|
|
/// # extern crate futures;
|
|
|
|
/// # use futures::future::Future;
|
|
|
|
/// use actix_web::AsyncResponder;
|
|
|
|
/// use futures::future::result;
|
|
|
|
/// use actix_web::{Either, Error, HttpRequest, HttpResponse, httpcodes};
|
|
|
|
///
|
|
|
|
/// type RegisterResult = Either<HttpResponse, Box<Future<Item=HttpResponse, Error=Error>>>;
|
|
|
|
///
|
2018-03-11 17:28:22 +01:00
|
|
|
///
|
2018-03-10 19:12:44 +01:00
|
|
|
/// fn index(req: HttpRequest) -> RegisterResult {
|
2018-03-11 17:28:22 +01:00
|
|
|
/// if is_a_variant() { // <- choose variant A
|
2018-03-10 19:12:44 +01:00
|
|
|
/// Either::A(
|
|
|
|
/// httpcodes::HttpBadRequest.with_body("Bad data"))
|
|
|
|
/// } else {
|
|
|
|
/// Either::B( // <- variant B
|
|
|
|
/// result(HttpResponse::Ok()
|
|
|
|
/// .content_type("text/html")
|
|
|
|
/// .body(format!("Hello!"))
|
|
|
|
/// .map_err(|e| e.into())).responder())
|
|
|
|
/// }
|
|
|
|
/// }
|
2018-03-11 17:28:22 +01:00
|
|
|
/// # fn is_a_variant() -> bool { true }
|
2018-03-10 19:12:44 +01:00
|
|
|
/// # fn main() {}
|
|
|
|
/// ```
|
2018-03-10 18:39:43 +01:00
|
|
|
#[derive(Debug)]
|
|
|
|
pub enum Either<A, B> {
|
|
|
|
/// First branch of the type
|
|
|
|
A(A),
|
|
|
|
/// Second branch of the type
|
|
|
|
B(B),
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<A, B> Responder for Either<A, B>
|
|
|
|
where A: Responder, B: Responder
|
|
|
|
{
|
|
|
|
type Item = Reply;
|
|
|
|
type Error = Error;
|
|
|
|
|
|
|
|
fn respond_to(self, req: HttpRequest) -> Result<Reply, Error> {
|
|
|
|
match self {
|
|
|
|
Either::A(a) => match a.respond_to(req) {
|
|
|
|
Ok(val) => Ok(val.into()),
|
|
|
|
Err(err) => Err(err.into()),
|
|
|
|
},
|
|
|
|
Either::B(b) => match b.respond_to(req) {
|
|
|
|
Ok(val) => Ok(val.into()),
|
|
|
|
Err(err) => Err(err.into()),
|
|
|
|
},
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
2017-12-21 08:19:21 +01:00
|
|
|
#[doc(hidden)]
|
2018-01-15 22:47:25 +01:00
|
|
|
/// Convenience trait that convert `Future` object into `Boxed` future
|
2017-12-21 05:30:54 +01:00
|
|
|
pub trait AsyncResponder<I, E>: Sized {
|
|
|
|
fn responder(self) -> Box<Future<Item=I, Error=E>>;
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<F, I, E> AsyncResponder<I, E> for F
|
|
|
|
where F: Future<Item=I, Error=E> + 'static,
|
|
|
|
I: Responder + 'static,
|
|
|
|
E: Into<Error> + 'static,
|
|
|
|
{
|
|
|
|
fn responder(self) -> Box<Future<Item=I, Error=E>> {
|
|
|
|
Box::new(self)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-11-29 22:26:55 +01:00
|
|
|
/// Handler<S> for Fn()
|
|
|
|
impl<F, R, S> Handler<S> for F
|
2017-11-27 06:18:38 +01:00
|
|
|
where F: Fn(HttpRequest<S>) -> R + 'static,
|
2017-12-14 18:43:42 +01:00
|
|
|
R: Responder + 'static
|
2017-10-15 23:17:41 +02:00
|
|
|
{
|
2017-11-29 22:26:55 +01:00
|
|
|
type Result = R;
|
2017-10-15 23:17:41 +02:00
|
|
|
|
2017-12-26 18:00:45 +01:00
|
|
|
fn handle(&mut self, req: HttpRequest<S>) -> R {
|
2017-11-29 22:26:55 +01:00
|
|
|
(self)(req)
|
2017-10-15 23:17:41 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-11-29 22:26:55 +01:00
|
|
|
/// Represents response process.
|
|
|
|
pub struct Reply(ReplyItem);
|
2017-11-29 04:49:17 +01:00
|
|
|
|
2017-12-01 00:13:56 +01:00
|
|
|
pub(crate) enum ReplyItem {
|
2017-12-16 01:24:15 +01:00
|
|
|
Message(HttpResponse),
|
2017-11-30 23:42:20 +01:00
|
|
|
Future(Box<Future<Item=HttpResponse, Error=Error>>),
|
2017-11-29 04:49:17 +01:00
|
|
|
}
|
|
|
|
|
2017-11-29 22:26:55 +01:00
|
|
|
impl Reply {
|
2017-11-29 04:49:17 +01:00
|
|
|
|
|
|
|
/// Create async response
|
2017-12-13 06:32:58 +01:00
|
|
|
#[inline]
|
2017-11-30 23:42:20 +01:00
|
|
|
pub fn async<F>(fut: F) -> Reply
|
|
|
|
where F: Future<Item=HttpResponse, Error=Error> + 'static
|
2017-11-29 04:49:17 +01:00
|
|
|
{
|
2017-11-30 23:42:20 +01:00
|
|
|
Reply(ReplyItem::Future(Box::new(fut)))
|
2017-11-29 04:49:17 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Send response
|
2017-12-13 06:32:58 +01:00
|
|
|
#[inline]
|
2017-12-01 00:13:56 +01:00
|
|
|
pub fn response<R: Into<HttpResponse>>(response: R) -> Reply {
|
2017-12-16 01:24:15 +01:00
|
|
|
Reply(ReplyItem::Message(response.into()))
|
2017-11-29 04:49:17 +01:00
|
|
|
}
|
|
|
|
|
2017-12-13 06:32:58 +01:00
|
|
|
#[inline]
|
2017-12-01 00:13:56 +01:00
|
|
|
pub(crate) fn into(self) -> ReplyItem {
|
|
|
|
self.0
|
2017-11-29 04:49:17 +01:00
|
|
|
}
|
2017-12-09 22:25:06 +01:00
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
pub(crate) fn as_response(&self) -> Option<&HttpResponse> {
|
|
|
|
match self.0 {
|
|
|
|
ReplyItem::Message(ref resp) => Some(resp),
|
|
|
|
_ => None,
|
|
|
|
}
|
|
|
|
}
|
2017-11-29 04:49:17 +01:00
|
|
|
}
|
|
|
|
|
2017-12-14 18:43:42 +01:00
|
|
|
impl Responder for Reply {
|
2017-12-03 23:22:04 +01:00
|
|
|
type Item = Reply;
|
|
|
|
type Error = Error;
|
|
|
|
|
2017-12-14 18:43:42 +01:00
|
|
|
fn respond_to(self, _: HttpRequest) -> Result<Reply, Error> {
|
2017-12-03 23:22:04 +01:00
|
|
|
Ok(self)
|
2017-12-03 01:37:21 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-12-14 18:43:42 +01:00
|
|
|
impl Responder for HttpResponse {
|
2017-12-03 23:22:04 +01:00
|
|
|
type Item = Reply;
|
|
|
|
type Error = Error;
|
|
|
|
|
2017-12-16 05:00:12 +01:00
|
|
|
#[inline]
|
2017-12-14 18:43:42 +01:00
|
|
|
fn respond_to(self, _: HttpRequest) -> Result<Reply, Error> {
|
2017-12-16 01:24:15 +01:00
|
|
|
Ok(Reply(ReplyItem::Message(self)))
|
2017-10-15 23:17:41 +02:00
|
|
|
}
|
|
|
|
}
|
2017-11-29 19:31:24 +01:00
|
|
|
|
2017-12-03 23:22:04 +01:00
|
|
|
impl From<HttpResponse> for Reply {
|
|
|
|
|
2017-12-16 05:00:12 +01:00
|
|
|
#[inline]
|
2017-12-03 23:22:04 +01:00
|
|
|
fn from(resp: HttpResponse) -> Reply {
|
2017-12-16 01:24:15 +01:00
|
|
|
Reply(ReplyItem::Message(resp))
|
2017-12-02 06:29:22 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-12-14 18:43:42 +01:00
|
|
|
impl<T: Responder, E: Into<Error>> Responder for Result<T, E>
|
2017-12-04 01:57:25 +01:00
|
|
|
{
|
2017-12-14 18:43:42 +01:00
|
|
|
type Item = <T as Responder>::Item;
|
2017-12-04 01:57:25 +01:00
|
|
|
type Error = Error;
|
2017-12-03 23:22:04 +01:00
|
|
|
|
2017-12-14 18:43:42 +01:00
|
|
|
fn respond_to(self, req: HttpRequest) -> Result<Self::Item, Self::Error> {
|
2017-12-03 01:37:21 +01:00
|
|
|
match self {
|
2017-12-14 18:43:42 +01:00
|
|
|
Ok(val) => match val.respond_to(req) {
|
2017-12-04 01:57:25 +01:00
|
|
|
Ok(val) => Ok(val),
|
|
|
|
Err(err) => Err(err.into()),
|
|
|
|
},
|
|
|
|
Err(err) => Err(err.into()),
|
2017-12-03 01:37:21 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-12-03 23:22:04 +01:00
|
|
|
impl<E: Into<Error>> From<Result<Reply, E>> for Reply {
|
2018-01-03 08:43:17 +01:00
|
|
|
#[inline]
|
2017-12-03 23:22:04 +01:00
|
|
|
fn from(res: Result<Reply, E>) -> Self {
|
2017-11-29 19:31:24 +01:00
|
|
|
match res {
|
|
|
|
Ok(val) => val,
|
2017-12-16 01:24:15 +01:00
|
|
|
Err(err) => Reply(ReplyItem::Message(err.into().into())),
|
2017-12-03 01:37:21 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-01-03 08:43:17 +01:00
|
|
|
impl<E: Into<Error>> From<Result<HttpResponse, E>> for Reply {
|
|
|
|
#[inline]
|
|
|
|
fn from(res: Result<HttpResponse, E>) -> Self {
|
|
|
|
match res {
|
|
|
|
Ok(val) => Reply(ReplyItem::Message(val)),
|
|
|
|
Err(err) => Reply(ReplyItem::Message(err.into().into())),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl From<Box<Future<Item=HttpResponse, Error=Error>>> for Reply {
|
|
|
|
#[inline]
|
|
|
|
fn from(fut: Box<Future<Item=HttpResponse, Error=Error>>) -> Reply {
|
|
|
|
Reply(ReplyItem::Future(fut))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-12-21 00:26:28 +01:00
|
|
|
impl<I, E> Responder for Box<Future<Item=I, Error=E>>
|
|
|
|
where I: Responder + 'static,
|
|
|
|
E: Into<Error> + 'static
|
2017-12-01 00:13:56 +01:00
|
|
|
{
|
2017-12-03 23:22:04 +01:00
|
|
|
type Item = Reply;
|
|
|
|
type Error = Error;
|
|
|
|
|
2017-12-16 05:00:12 +01:00
|
|
|
#[inline]
|
2017-12-21 00:26:28 +01:00
|
|
|
fn respond_to(self, req: HttpRequest) -> Result<Reply, Error> {
|
|
|
|
let fut = self.map_err(|e| e.into())
|
|
|
|
.then(move |r| {
|
|
|
|
match r.respond_to(req) {
|
|
|
|
Ok(reply) => match reply.into().0 {
|
|
|
|
ReplyItem::Message(resp) => ok(resp),
|
|
|
|
_ => panic!("Nested async replies are not supported"),
|
|
|
|
},
|
|
|
|
Err(e) => err(e),
|
|
|
|
}
|
|
|
|
});
|
|
|
|
Ok(Reply::async(fut))
|
2017-12-01 00:13:56 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-01-15 22:47:25 +01:00
|
|
|
/// Trait defines object that could be registered as resource route
|
2017-11-29 22:26:55 +01:00
|
|
|
pub(crate) trait RouteHandler<S>: 'static {
|
2017-12-26 18:00:45 +01:00
|
|
|
fn handle(&mut self, req: HttpRequest<S>) -> Reply;
|
2017-11-29 22:26:55 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Route handler wrapper for Handler
|
|
|
|
pub(crate)
|
|
|
|
struct WrapHandler<S, H, R>
|
|
|
|
where H: Handler<S, Result=R>,
|
2017-12-14 18:43:42 +01:00
|
|
|
R: Responder,
|
2017-11-29 22:26:55 +01:00
|
|
|
S: 'static,
|
|
|
|
{
|
|
|
|
h: H,
|
|
|
|
s: PhantomData<S>,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<S, H, R> WrapHandler<S, H, R>
|
|
|
|
where H: Handler<S, Result=R>,
|
2017-12-14 18:43:42 +01:00
|
|
|
R: Responder,
|
2017-11-29 22:26:55 +01:00
|
|
|
S: 'static,
|
|
|
|
{
|
|
|
|
pub fn new(h: H) -> Self {
|
2018-02-26 23:33:56 +01:00
|
|
|
WrapHandler{h, s: PhantomData}
|
2017-11-29 22:26:55 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<S, H, R> RouteHandler<S> for WrapHandler<S, H, R>
|
|
|
|
where H: Handler<S, Result=R>,
|
2017-12-14 18:43:42 +01:00
|
|
|
R: Responder + 'static,
|
2017-11-29 22:26:55 +01:00
|
|
|
S: 'static,
|
|
|
|
{
|
2017-12-26 18:00:45 +01:00
|
|
|
fn handle(&mut self, req: HttpRequest<S>) -> Reply {
|
2018-02-26 23:33:56 +01:00
|
|
|
let req2 = req.without_state();
|
2017-12-14 18:43:42 +01:00
|
|
|
match self.h.handle(req).respond_to(req2) {
|
2017-12-03 23:22:04 +01:00
|
|
|
Ok(reply) => reply.into(),
|
|
|
|
Err(err) => Reply::response(err.into()),
|
|
|
|
}
|
2017-11-29 22:26:55 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Async route handler
|
|
|
|
pub(crate)
|
2017-12-20 21:51:39 +01:00
|
|
|
struct AsyncHandler<S, H, F, R, E>
|
|
|
|
where H: Fn(HttpRequest<S>) -> F + 'static,
|
|
|
|
F: Future<Item=R, Error=E> + 'static,
|
|
|
|
R: Responder + 'static,
|
|
|
|
E: Into<Error> + 'static,
|
2017-11-29 22:26:55 +01:00
|
|
|
S: 'static,
|
|
|
|
{
|
2017-12-20 21:51:39 +01:00
|
|
|
h: Box<H>,
|
2017-11-29 22:26:55 +01:00
|
|
|
s: PhantomData<S>,
|
|
|
|
}
|
|
|
|
|
2017-12-20 21:51:39 +01:00
|
|
|
impl<S, H, F, R, E> AsyncHandler<S, H, F, R, E>
|
|
|
|
where H: Fn(HttpRequest<S>) -> F + 'static,
|
|
|
|
F: Future<Item=R, Error=E> + 'static,
|
|
|
|
R: Responder + 'static,
|
|
|
|
E: Into<Error> + 'static,
|
2017-11-29 22:26:55 +01:00
|
|
|
S: 'static,
|
|
|
|
{
|
2017-12-20 21:51:39 +01:00
|
|
|
pub fn new(h: H) -> Self {
|
|
|
|
AsyncHandler{h: Box::new(h), s: PhantomData}
|
2017-11-29 22:26:55 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-12-20 21:51:39 +01:00
|
|
|
impl<S, H, F, R, E> RouteHandler<S> for AsyncHandler<S, H, F, R, E>
|
|
|
|
where H: Fn(HttpRequest<S>) -> F + 'static,
|
|
|
|
F: Future<Item=R, Error=E> + 'static,
|
|
|
|
R: Responder + 'static,
|
|
|
|
E: Into<Error> + 'static,
|
2017-11-29 22:26:55 +01:00
|
|
|
S: 'static,
|
|
|
|
{
|
2017-12-26 18:00:45 +01:00
|
|
|
fn handle(&mut self, req: HttpRequest<S>) -> Reply {
|
2018-02-26 23:33:56 +01:00
|
|
|
let req2 = req.without_state();
|
2017-12-20 21:51:39 +01:00
|
|
|
let fut = (self.h)(req)
|
|
|
|
.map_err(|e| e.into())
|
|
|
|
.then(move |r| {
|
|
|
|
match r.respond_to(req2) {
|
|
|
|
Ok(reply) => match reply.into().0 {
|
|
|
|
ReplyItem::Message(resp) => ok(resp),
|
|
|
|
_ => panic!("Nested async replies are not supported"),
|
2017-12-20 22:23:50 +01:00
|
|
|
},
|
2017-12-20 21:51:39 +01:00
|
|
|
Err(e) => err(e),
|
|
|
|
}
|
|
|
|
});
|
|
|
|
Reply::async(fut)
|
2017-11-29 22:26:55 +01:00
|
|
|
}
|
|
|
|
}
|
2017-12-04 03:51:52 +01:00
|
|
|
|
2017-12-09 20:55:55 +01:00
|
|
|
/// Path normalization helper
|
|
|
|
///
|
|
|
|
/// By normalizing it means:
|
2017-12-09 20:39:13 +01:00
|
|
|
///
|
|
|
|
/// - Add a trailing slash to the path.
|
2018-02-21 23:53:42 +01:00
|
|
|
/// - Remove a trailing slash from the path.
|
2017-12-09 20:39:13 +01:00
|
|
|
/// - Double slashes are replaced by one.
|
|
|
|
///
|
|
|
|
/// The handler returns as soon as it finds a path that resolves
|
2017-12-09 20:55:55 +01:00
|
|
|
/// correctly. The order if all enable is 1) merge, 3) both merge and append
|
|
|
|
/// and 3) append. If the path resolves with
|
2017-12-09 20:39:13 +01:00
|
|
|
/// at least one of those conditions, it will redirect to the new path.
|
|
|
|
///
|
|
|
|
/// If *append* is *true* append slash when needed. If a resource is
|
|
|
|
/// defined with trailing slash and the request comes without it, it will
|
|
|
|
/// append it automatically.
|
|
|
|
///
|
|
|
|
/// If *merge* is *true*, merge multiple consecutive slashes in the path into one.
|
|
|
|
///
|
|
|
|
/// This handler designed to be use as a handler for application's *default resource*.
|
2017-12-09 20:55:55 +01:00
|
|
|
///
|
|
|
|
/// ```rust
|
|
|
|
/// # extern crate actix_web;
|
|
|
|
/// # #[macro_use] extern crate serde_derive;
|
|
|
|
/// # use actix_web::*;
|
|
|
|
/// #
|
|
|
|
/// # fn index(req: HttpRequest) -> httpcodes::StaticResponse {
|
2018-03-02 04:12:59 +01:00
|
|
|
/// # httpcodes::HttpOk
|
2017-12-09 20:55:55 +01:00
|
|
|
/// # }
|
|
|
|
/// fn main() {
|
2017-12-11 23:16:29 +01:00
|
|
|
/// let app = Application::new()
|
2017-12-09 20:55:55 +01:00
|
|
|
/// .resource("/test/", |r| r.f(index))
|
|
|
|
/// .default_resource(|r| r.h(NormalizePath::default()))
|
|
|
|
/// .finish();
|
|
|
|
/// }
|
|
|
|
/// ```
|
|
|
|
/// In this example `/test`, `/test///` will be redirected to `/test/` url.
|
2017-12-09 20:39:13 +01:00
|
|
|
pub struct NormalizePath {
|
|
|
|
append: bool,
|
|
|
|
merge: bool,
|
|
|
|
re_merge: Regex,
|
|
|
|
redirect: StatusCode,
|
|
|
|
not_found: StatusCode,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Default for NormalizePath {
|
2017-12-09 20:55:55 +01:00
|
|
|
/// Create default `NormalizePath` instance, *append* is set to *true*,
|
|
|
|
/// *merge* is set to *true* and *redirect* is set to `StatusCode::MOVED_PERMANENTLY`
|
2017-12-09 20:39:13 +01:00
|
|
|
fn default() -> NormalizePath {
|
|
|
|
NormalizePath {
|
|
|
|
append: true,
|
|
|
|
merge: true,
|
|
|
|
re_merge: Regex::new("//+").unwrap(),
|
|
|
|
redirect: StatusCode::MOVED_PERMANENTLY,
|
|
|
|
not_found: StatusCode::NOT_FOUND,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl NormalizePath {
|
2018-01-16 19:59:33 +01:00
|
|
|
/// Create new `NormalizePath` instance
|
2017-12-09 20:39:13 +01:00
|
|
|
pub fn new(append: bool, merge: bool, redirect: StatusCode) -> NormalizePath {
|
|
|
|
NormalizePath {
|
2018-02-26 23:33:56 +01:00
|
|
|
append,
|
|
|
|
merge,
|
|
|
|
redirect,
|
2017-12-09 20:39:13 +01:00
|
|
|
re_merge: Regex::new("//+").unwrap(),
|
|
|
|
not_found: StatusCode::NOT_FOUND,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<S> Handler<S> for NormalizePath {
|
|
|
|
type Result = Result<HttpResponse, HttpError>;
|
|
|
|
|
2017-12-26 18:00:45 +01:00
|
|
|
fn handle(&mut self, req: HttpRequest<S>) -> Self::Result {
|
2017-12-09 20:39:13 +01:00
|
|
|
if let Some(router) = req.router() {
|
2017-12-09 22:25:06 +01:00
|
|
|
let query = req.query_string();
|
2017-12-09 20:39:13 +01:00
|
|
|
if self.merge {
|
|
|
|
// merge slashes
|
|
|
|
let p = self.re_merge.replace_all(req.path(), "/");
|
|
|
|
if p.len() != req.path().len() {
|
|
|
|
if router.has_route(p.as_ref()) {
|
2017-12-09 22:25:06 +01:00
|
|
|
let p = if !query.is_empty() { p + "?" + query } else { p };
|
2017-12-09 20:39:13 +01:00
|
|
|
return HttpResponse::build(self.redirect)
|
|
|
|
.header(header::LOCATION, p.as_ref())
|
|
|
|
.body(Body::Empty);
|
|
|
|
}
|
|
|
|
// merge slashes and append trailing slash
|
|
|
|
if self.append && !p.ends_with('/') {
|
|
|
|
let p = p.as_ref().to_owned() + "/";
|
|
|
|
if router.has_route(&p) {
|
2017-12-09 22:25:06 +01:00
|
|
|
let p = if !query.is_empty() { p + "?" + query } else { p };
|
2017-12-09 20:39:13 +01:00
|
|
|
return HttpResponse::build(self.redirect)
|
|
|
|
.header(header::LOCATION, p.as_str())
|
|
|
|
.body(Body::Empty);
|
|
|
|
}
|
|
|
|
}
|
2018-02-19 23:27:36 +01:00
|
|
|
|
|
|
|
// try to remove trailing slash
|
|
|
|
if p.ends_with('/') {
|
|
|
|
let p = p.as_ref().trim_right_matches('/');
|
2018-02-19 23:57:57 +01:00
|
|
|
if router.has_route(p) {
|
|
|
|
let mut req = HttpResponse::build(self.redirect);
|
|
|
|
return if !query.is_empty() {
|
|
|
|
req.header(header::LOCATION, (p.to_owned() + "?" + query).as_str())
|
|
|
|
} else {
|
|
|
|
req.header(header::LOCATION, p)
|
|
|
|
}
|
|
|
|
.body(Body::Empty);
|
2018-02-19 23:27:36 +01:00
|
|
|
}
|
|
|
|
}
|
2018-02-21 23:53:42 +01:00
|
|
|
} else if p.ends_with('/') {
|
|
|
|
// try to remove trailing slash
|
|
|
|
let p = p.as_ref().trim_right_matches('/');
|
|
|
|
if router.has_route(p) {
|
|
|
|
let mut req = HttpResponse::build(self.redirect);
|
|
|
|
return if !query.is_empty() {
|
|
|
|
req.header(header::LOCATION, (p.to_owned() + "?" + query).as_str())
|
|
|
|
} else {
|
|
|
|
req.header(header::LOCATION, p)
|
|
|
|
}
|
|
|
|
.body(Body::Empty);
|
|
|
|
}
|
2017-12-09 20:39:13 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
// append trailing slash
|
|
|
|
if self.append && !req.path().ends_with('/') {
|
|
|
|
let p = req.path().to_owned() + "/";
|
|
|
|
if router.has_route(&p) {
|
2017-12-09 22:25:06 +01:00
|
|
|
let p = if !query.is_empty() { p + "?" + query } else { p };
|
2017-12-09 20:39:13 +01:00
|
|
|
return HttpResponse::build(self.redirect)
|
|
|
|
.header(header::LOCATION, p.as_str())
|
|
|
|
.body(Body::Empty);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
Ok(HttpResponse::new(self.not_found, Body::Empty))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-12-04 03:51:52 +01:00
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
|
|
|
use super::*;
|
2017-12-09 22:25:06 +01:00
|
|
|
use http::{header, Method};
|
2017-12-27 04:48:02 +01:00
|
|
|
use test::TestRequest;
|
2017-12-09 22:25:06 +01:00
|
|
|
use application::Application;
|
2017-12-04 03:51:52 +01:00
|
|
|
|
2017-12-09 22:25:06 +01:00
|
|
|
fn index(_req: HttpRequest) -> HttpResponse {
|
|
|
|
HttpResponse::new(StatusCode::OK, Body::Empty)
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_normalize_path_trailing_slashes() {
|
2017-12-26 18:00:45 +01:00
|
|
|
let mut app = Application::new()
|
2017-12-09 22:25:06 +01:00
|
|
|
.resource("/resource1", |r| r.method(Method::GET).f(index))
|
|
|
|
.resource("/resource2/", |r| r.method(Method::GET).f(index))
|
|
|
|
.default_resource(|r| r.h(NormalizePath::default()))
|
|
|
|
.finish();
|
|
|
|
|
|
|
|
// trailing slashes
|
2018-02-21 23:53:42 +01:00
|
|
|
let params =
|
|
|
|
vec![("/resource1", "", StatusCode::OK),
|
|
|
|
("/resource1/", "/resource1", StatusCode::MOVED_PERMANENTLY),
|
|
|
|
("/resource2", "/resource2/", StatusCode::MOVED_PERMANENTLY),
|
|
|
|
("/resource2/", "", StatusCode::OK),
|
|
|
|
("/resource1?p1=1&p2=2", "", StatusCode::OK),
|
|
|
|
("/resource1/?p1=1&p2=2", "/resource1?p1=1&p2=2", StatusCode::MOVED_PERMANENTLY),
|
|
|
|
("/resource2?p1=1&p2=2", "/resource2/?p1=1&p2=2",
|
|
|
|
StatusCode::MOVED_PERMANENTLY),
|
|
|
|
("/resource2/?p1=1&p2=2", "", StatusCode::OK)
|
|
|
|
];
|
2017-12-09 22:25:06 +01:00
|
|
|
for (path, target, code) in params {
|
2017-12-27 04:48:02 +01:00
|
|
|
let req = app.prepare_request(TestRequest::with_uri(path).finish());
|
2017-12-09 22:25:06 +01:00
|
|
|
let resp = app.run(req);
|
|
|
|
let r = resp.as_response().unwrap();
|
|
|
|
assert_eq!(r.status(), code);
|
|
|
|
if !target.is_empty() {
|
|
|
|
assert_eq!(
|
|
|
|
target,
|
|
|
|
r.headers().get(header::LOCATION).unwrap().to_str().unwrap());
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_normalize_path_trailing_slashes_disabled() {
|
2017-12-26 18:00:45 +01:00
|
|
|
let mut app = Application::new()
|
2017-12-09 22:25:06 +01:00
|
|
|
.resource("/resource1", |r| r.method(Method::GET).f(index))
|
|
|
|
.resource("/resource2/", |r| r.method(Method::GET).f(index))
|
|
|
|
.default_resource(|r| r.h(
|
|
|
|
NormalizePath::new(false, true, StatusCode::MOVED_PERMANENTLY)))
|
|
|
|
.finish();
|
|
|
|
|
|
|
|
// trailing slashes
|
|
|
|
let params = vec![("/resource1", StatusCode::OK),
|
2018-02-21 23:53:42 +01:00
|
|
|
("/resource1/", StatusCode::MOVED_PERMANENTLY),
|
2017-12-09 22:25:06 +01:00
|
|
|
("/resource2", StatusCode::NOT_FOUND),
|
|
|
|
("/resource2/", StatusCode::OK),
|
|
|
|
("/resource1?p1=1&p2=2", StatusCode::OK),
|
2018-02-21 23:53:42 +01:00
|
|
|
("/resource1/?p1=1&p2=2", StatusCode::MOVED_PERMANENTLY),
|
2017-12-09 22:25:06 +01:00
|
|
|
("/resource2?p1=1&p2=2", StatusCode::NOT_FOUND),
|
|
|
|
("/resource2/?p1=1&p2=2", StatusCode::OK)
|
|
|
|
];
|
|
|
|
for (path, code) in params {
|
2017-12-27 04:48:02 +01:00
|
|
|
let req = app.prepare_request(TestRequest::with_uri(path).finish());
|
2017-12-09 22:25:06 +01:00
|
|
|
let resp = app.run(req);
|
|
|
|
let r = resp.as_response().unwrap();
|
|
|
|
assert_eq!(r.status(), code);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_normalize_path_merge_slashes() {
|
2017-12-26 18:00:45 +01:00
|
|
|
let mut app = Application::new()
|
2017-12-09 22:25:06 +01:00
|
|
|
.resource("/resource1", |r| r.method(Method::GET).f(index))
|
|
|
|
.resource("/resource1/a/b", |r| r.method(Method::GET).f(index))
|
|
|
|
.default_resource(|r| r.h(NormalizePath::default()))
|
|
|
|
.finish();
|
|
|
|
|
|
|
|
// trailing slashes
|
|
|
|
let params = vec![
|
|
|
|
("/resource1/a/b", "", StatusCode::OK),
|
2018-02-21 23:53:42 +01:00
|
|
|
("/resource1/", "/resource1", StatusCode::MOVED_PERMANENTLY),
|
|
|
|
("/resource1//", "/resource1", StatusCode::MOVED_PERMANENTLY),
|
2017-12-09 22:25:06 +01:00
|
|
|
("//resource1//a//b", "/resource1/a/b", StatusCode::MOVED_PERMANENTLY),
|
2018-02-19 23:27:36 +01:00
|
|
|
("//resource1//a//b/", "/resource1/a/b", StatusCode::MOVED_PERMANENTLY),
|
2018-02-20 22:03:21 +01:00
|
|
|
("//resource1//a//b//", "/resource1/a/b", StatusCode::MOVED_PERMANENTLY),
|
2017-12-09 22:25:06 +01:00
|
|
|
("///resource1//a//b", "/resource1/a/b", StatusCode::MOVED_PERMANENTLY),
|
|
|
|
("/////resource1/a///b", "/resource1/a/b", StatusCode::MOVED_PERMANENTLY),
|
2018-02-19 23:27:36 +01:00
|
|
|
("/////resource1/a//b/", "/resource1/a/b", StatusCode::MOVED_PERMANENTLY),
|
2017-12-09 22:25:06 +01:00
|
|
|
("/resource1/a/b?p=1", "", StatusCode::OK),
|
|
|
|
("//resource1//a//b?p=1", "/resource1/a/b?p=1", StatusCode::MOVED_PERMANENTLY),
|
2018-02-19 23:27:36 +01:00
|
|
|
("//resource1//a//b/?p=1", "/resource1/a/b?p=1", StatusCode::MOVED_PERMANENTLY),
|
2017-12-09 22:25:06 +01:00
|
|
|
("///resource1//a//b?p=1", "/resource1/a/b?p=1", StatusCode::MOVED_PERMANENTLY),
|
|
|
|
("/////resource1/a///b?p=1", "/resource1/a/b?p=1", StatusCode::MOVED_PERMANENTLY),
|
2018-02-19 23:27:36 +01:00
|
|
|
("/////resource1/a//b/?p=1", "/resource1/a/b?p=1", StatusCode::MOVED_PERMANENTLY),
|
2018-02-20 22:03:21 +01:00
|
|
|
("/////resource1/a//b//?p=1", "/resource1/a/b?p=1", StatusCode::MOVED_PERMANENTLY),
|
2017-12-09 22:25:06 +01:00
|
|
|
];
|
|
|
|
for (path, target, code) in params {
|
2017-12-27 04:48:02 +01:00
|
|
|
let req = app.prepare_request(TestRequest::with_uri(path).finish());
|
2017-12-09 22:25:06 +01:00
|
|
|
let resp = app.run(req);
|
|
|
|
let r = resp.as_response().unwrap();
|
|
|
|
assert_eq!(r.status(), code);
|
|
|
|
if !target.is_empty() {
|
|
|
|
assert_eq!(
|
|
|
|
target,
|
|
|
|
r.headers().get(header::LOCATION).unwrap().to_str().unwrap());
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_normalize_path_merge_and_append_slashes() {
|
2017-12-26 18:00:45 +01:00
|
|
|
let mut app = Application::new()
|
2017-12-09 22:25:06 +01:00
|
|
|
.resource("/resource1", |r| r.method(Method::GET).f(index))
|
|
|
|
.resource("/resource2/", |r| r.method(Method::GET).f(index))
|
|
|
|
.resource("/resource1/a/b", |r| r.method(Method::GET).f(index))
|
|
|
|
.resource("/resource2/a/b/", |r| r.method(Method::GET).f(index))
|
|
|
|
.default_resource(|r| r.h(NormalizePath::default()))
|
|
|
|
.finish();
|
|
|
|
|
|
|
|
// trailing slashes
|
|
|
|
let params = vec![
|
|
|
|
("/resource1/a/b", "", StatusCode::OK),
|
2018-02-21 23:53:42 +01:00
|
|
|
("/resource1/a/b/", "/resource1/a/b", StatusCode::MOVED_PERMANENTLY),
|
2017-12-09 22:25:06 +01:00
|
|
|
("//resource2//a//b", "/resource2/a/b/", StatusCode::MOVED_PERMANENTLY),
|
|
|
|
("//resource2//a//b/", "/resource2/a/b/", StatusCode::MOVED_PERMANENTLY),
|
2018-02-20 22:03:21 +01:00
|
|
|
("//resource2//a//b//", "/resource2/a/b/", StatusCode::MOVED_PERMANENTLY),
|
2017-12-09 22:25:06 +01:00
|
|
|
("///resource1//a//b", "/resource1/a/b", StatusCode::MOVED_PERMANENTLY),
|
2018-02-19 23:27:36 +01:00
|
|
|
("///resource1//a//b/", "/resource1/a/b", StatusCode::MOVED_PERMANENTLY),
|
2017-12-09 22:25:06 +01:00
|
|
|
("/////resource1/a///b", "/resource1/a/b", StatusCode::MOVED_PERMANENTLY),
|
2018-02-19 23:27:36 +01:00
|
|
|
("/////resource1/a///b/", "/resource1/a/b", StatusCode::MOVED_PERMANENTLY),
|
2017-12-09 22:25:06 +01:00
|
|
|
("/resource2/a/b", "/resource2/a/b/", StatusCode::MOVED_PERMANENTLY),
|
|
|
|
("/resource2/a/b/", "", StatusCode::OK),
|
|
|
|
("//resource2//a//b", "/resource2/a/b/", StatusCode::MOVED_PERMANENTLY),
|
|
|
|
("//resource2//a//b/", "/resource2/a/b/", StatusCode::MOVED_PERMANENTLY),
|
|
|
|
("///resource2//a//b", "/resource2/a/b/", StatusCode::MOVED_PERMANENTLY),
|
|
|
|
("///resource2//a//b/", "/resource2/a/b/", StatusCode::MOVED_PERMANENTLY),
|
|
|
|
("/////resource2/a///b", "/resource2/a/b/", StatusCode::MOVED_PERMANENTLY),
|
|
|
|
("/////resource2/a///b/", "/resource2/a/b/", StatusCode::MOVED_PERMANENTLY),
|
|
|
|
("/resource1/a/b?p=1", "", StatusCode::OK),
|
2018-02-21 23:53:42 +01:00
|
|
|
("/resource1/a/b/?p=1", "/resource1/a/b?p=1", StatusCode::MOVED_PERMANENTLY),
|
2017-12-09 22:25:06 +01:00
|
|
|
("//resource2//a//b?p=1", "/resource2/a/b/?p=1", StatusCode::MOVED_PERMANENTLY),
|
|
|
|
("//resource2//a//b/?p=1", "/resource2/a/b/?p=1", StatusCode::MOVED_PERMANENTLY),
|
|
|
|
("///resource1//a//b?p=1", "/resource1/a/b?p=1", StatusCode::MOVED_PERMANENTLY),
|
2018-02-19 23:27:36 +01:00
|
|
|
("///resource1//a//b/?p=1", "/resource1/a/b?p=1", StatusCode::MOVED_PERMANENTLY),
|
2017-12-09 22:25:06 +01:00
|
|
|
("/////resource1/a///b?p=1", "/resource1/a/b?p=1", StatusCode::MOVED_PERMANENTLY),
|
2018-02-19 23:27:36 +01:00
|
|
|
("/////resource1/a///b/?p=1", "/resource1/a/b?p=1", StatusCode::MOVED_PERMANENTLY),
|
2018-02-20 22:03:21 +01:00
|
|
|
("/////resource1/a///b//?p=1", "/resource1/a/b?p=1", StatusCode::MOVED_PERMANENTLY),
|
2017-12-09 22:25:06 +01:00
|
|
|
("/resource2/a/b?p=1", "/resource2/a/b/?p=1", StatusCode::MOVED_PERMANENTLY),
|
|
|
|
("//resource2//a//b?p=1", "/resource2/a/b/?p=1", StatusCode::MOVED_PERMANENTLY),
|
|
|
|
("//resource2//a//b/?p=1", "/resource2/a/b/?p=1", StatusCode::MOVED_PERMANENTLY),
|
|
|
|
("///resource2//a//b?p=1", "/resource2/a/b/?p=1", StatusCode::MOVED_PERMANENTLY),
|
|
|
|
("///resource2//a//b/?p=1", "/resource2/a/b/?p=1", StatusCode::MOVED_PERMANENTLY),
|
|
|
|
("/////resource2/a///b?p=1", "/resource2/a/b/?p=1", StatusCode::MOVED_PERMANENTLY),
|
|
|
|
("/////resource2/a///b/?p=1", "/resource2/a/b/?p=1", StatusCode::MOVED_PERMANENTLY),
|
|
|
|
];
|
|
|
|
for (path, target, code) in params {
|
2017-12-27 04:48:02 +01:00
|
|
|
let req = app.prepare_request(TestRequest::with_uri(path).finish());
|
2017-12-09 22:25:06 +01:00
|
|
|
let resp = app.run(req);
|
|
|
|
let r = resp.as_response().unwrap();
|
|
|
|
assert_eq!(r.status(), code);
|
|
|
|
if !target.is_empty() {
|
|
|
|
assert_eq!(
|
|
|
|
target, r.headers().get(header::LOCATION).unwrap().to_str().unwrap());
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
2017-12-04 03:51:52 +01:00
|
|
|
}
|