Skip to content

Commit

Permalink
Add Response::redirect
Browse files Browse the repository at this point in the history
and use it in the Redirect endpoint
  • Loading branch information
jbr committed Apr 21, 2020
1 parent 2003a99 commit bf7fbea
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 4 deletions.
5 changes: 1 addition & 4 deletions src/redirect.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
use crate::utils::BoxFuture;
use http_types::StatusCode;

use crate::{Endpoint, Request, Response};

/// Redirect a route to another route.
Expand Down Expand Up @@ -32,8 +30,7 @@ pub struct Redirect {

impl<State> Endpoint<State> for Redirect {
fn call<'a>(&'a self, _req: Request<State>) -> BoxFuture<'a, crate::Result<Response>> {
let res = Response::new(StatusCode::TemporaryRedirect)
.set_header("location".parse().unwrap(), self.location.clone());
let res = Response::redirect_temp(&self.location);
Box::pin(async move { Ok(res) })
}
}
46 changes: 46 additions & 0 deletions src/response/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,52 @@ impl Response {
}
}

/// Creates a response that represents a permanent redirect to `location`.
///
///
/// # Example
///
/// ```
/// # use tide::{Response, Request};
/// # fn canonicalize(uri: &url::Url) -> Option<&url::Url> { None }
/// # #[allow(dead_code)]
/// async fn route_handler(request: Request<()>) -> tide::Result<Response> {
/// if let Some(canonical_redirect) = canonicalize(request.uri()) {
/// Ok(Response::redirect_perm(canonical_redirect))
/// } else {
/// //...
/// # Ok(Response::new(http_types::StatusCode::Ok)) // ...
/// }
/// }
/// ```
pub fn redirect_perm(location: impl AsRef<str>) -> Self {
Response::new(StatusCode::PermanentRedirect)
.set_header("location".parse().unwrap(), location)
}

/// Creates a response that represents a temporary redirect to `location`.
///
///
/// # Example
///
/// ```
/// # use tide::{Response, Request};
/// # fn special_sale_today() -> Option<String> { None }
/// # #[allow(dead_code)]
/// async fn route_handler(request: Request<()>) -> tide::Result<Response> {
/// if let Some(sale_url) = special_sale_today() {
/// Ok(Response::redirect_temp(sale_url))
/// } else {
/// //...
/// # Ok(Response::new(http_types::StatusCode::Ok)) //...
/// }
/// }
/// ```
pub fn redirect_temp(location: impl AsRef<str>) -> Self {
Response::new(StatusCode::TemporaryRedirect)
.set_header("location".parse().unwrap(), location)
}

/// Returns the statuscode.
pub fn status(&self) -> http_types::StatusCode {
self.res.status()
Expand Down

0 comments on commit bf7fbea

Please sign in to comment.