Skip to content

Commit

Permalink
Add 302 redirect helper (#890)
Browse files Browse the repository at this point in the history
  • Loading branch information
SeanChao committed Aug 31, 2021
1 parent ffe49ab commit 4f42d76
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
16 changes: 16 additions & 0 deletions src/redirect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,22 @@ pub fn redirect(uri: impl AsLocation) -> impl Reply {
)
}

/// A simple `302` found redirect to a different location
///
/// # Example
///
/// ```
/// use warp::{http::Uri, Filter};
///
/// let route = warp::path("v1")
/// .map(|| {
/// warp::redirect::found(Uri::from_static("/v2"))
/// });
/// ```
pub fn found(uri: impl AsLocation) -> impl Reply {
reply::with_header(StatusCode::FOUND, header::LOCATION, uri.header_value())
}

/// A simple `303` redirect to a different location.
///
/// The HTTP method of the request to the new location will always be `GET`.
Expand Down
11 changes: 11 additions & 0 deletions tests/redirect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,17 @@ async fn redirect_uri() {
assert_eq!(resp.headers()["location"], "/over-there");
}

#[tokio::test]
async fn redirect_found_uri() {
let over_there = warp::any().map(|| warp::redirect::found(Uri::from_static("/over-there")));

let req = warp::test::request();
let resp = req.reply(&over_there).await;

assert_eq!(resp.status(), 302);
assert_eq!(resp.headers()["location"], "/over-there");
}

#[tokio::test]
async fn redirect_see_other_uri() {
let over_there = warp::any().map(|| warp::redirect::see_other(Uri::from_static("/over-there")));
Expand Down

0 comments on commit 4f42d76

Please sign in to comment.