Skip to content

Commit

Permalink
Merge pull request #435 from jbr/add_response_redirect
Browse files Browse the repository at this point in the history
Add Response::redirect
  • Loading branch information
yoshuawuyts authored Apr 22, 2020
2 parents e74cb4c + bf7fbea commit dd596a8
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 dd596a8

Please sign in to comment.