Skip to content
Open
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
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ type_complexity = "allow"

await_holding_lock = "warn"
dbg_macro = "warn"
empty_enums = "warn"
empty_enum = "warn"
enum_glob_use = "warn"
equatable_if_let = "warn"
exit = "warn"
Expand Down
5 changes: 5 additions & 0 deletions axum-core/src/response/into_response_parts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,11 @@ impl ResponseParts {
pub fn extensions_mut(&mut self) -> &mut Extensions {
self.res.extensions_mut()
}

/// Set the status code of the response.
pub fn set_status(&mut self, status: StatusCode) {
*self.res.status_mut() = status;
}
}

impl IntoResponseParts for HeaderMap {
Expand Down
36 changes: 35 additions & 1 deletion axum/src/response/redirect.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use axum_core::response::{IntoResponse, Response};
use axum_core::response::{IntoResponse, IntoResponseParts, Response, ResponseParts};
use http::{header::LOCATION, HeaderValue, StatusCode};

/// Response that redirects the request to another location.
Expand Down Expand Up @@ -93,8 +93,28 @@ impl IntoResponse for Redirect {
}
}

impl IntoResponseParts for Redirect {
type Error = Response;

fn into_response_parts(self, mut res: ResponseParts) -> Result<ResponseParts, Self::Error> {
match HeaderValue::try_from(self.location) {
Ok(location) => {
res.set_status(self.status_code);
res.headers_mut().insert(LOCATION, location);
Ok(res)
}
Err(error) => {
// If the URI is invalid, we return a 500 error response immediately
Err((StatusCode::INTERNAL_SERVER_ERROR, error.to_string()).into_response())
}
}
}
}

#[cfg(test)]
mod tests {
use crate::response::Html;

use super::Redirect;
use axum_core::response::IntoResponse;
use http::StatusCode;
Expand Down Expand Up @@ -135,4 +155,18 @@ mod tests {

assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
}

#[test]
fn as_response_parts() {
let response = (
Redirect::to(EXAMPLE_URL),
Html(format!(
r#"<p>Redirecting to <a href="{EXAMPLE_URL}">{EXAMPLE_URL}</a></p>"#
)),
)
.into_response();

assert_eq!(response.status(), StatusCode::SEE_OTHER);
assert_eq!(response.headers()[http::header::LOCATION], EXAMPLE_URL);
}
}