1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
use crate::{
http::{header, StatusCode},
Error, Response, Result,
};
/// A collection of functions used to generate redirect responses.
pub struct Redirect;
impl Redirect {
/// Returns a response that redirects the client to the specified `location`
/// with the status code `302 Found`.
///
/// # Errors
///
/// This function may return an error if the provided `location` cannot be
/// parsed into an HTTP header value.
pub fn found(location: &str) -> Result<Response> {
Self::with_status(location, StatusCode::FOUND)
}
/// Returns a response that redirects the client to the specified `location`
/// with the status code `303 See Other`.
///
/// # Errors
///
/// This function may return an error if the provided `location` cannot be
/// parsed into an HTTP header value.
pub fn see_other(location: &str) -> Result<Response> {
Self::with_status(location, StatusCode::SEE_OTHER)
}
/// Returns a response that redirects the client to the specified `location`
/// with the status code `307 Temporary Redirect`.
///
/// # Errors
///
/// This function may return an error if the provided `location` cannot be
/// parsed into an HTTP header value.
pub fn temporary(location: &str) -> Result<Response> {
Self::with_status(location, StatusCode::TEMPORARY_REDIRECT)
}
/// Returns a response that redirects the client to the specified `location`
/// with the status code `308 Permanent Redirect`.
///
/// # Errors
///
/// This function may return an error if the provided `location` cannot be
/// parsed into an HTTP header value.
pub fn permanent(location: &str) -> Result<Response> {
Self::with_status(location, StatusCode::PERMANENT_REDIRECT)
}
/// Returns a response that redirects the client to the specified `location`
/// with the status code `308 Permanent Redirect`.
///
/// # Errors
///
/// This function may return an error if the provided `location` cannot be
/// parsed into an HTTP header value or if provided `status` would not
/// result in a redirect.
pub fn with_status<T>(location: &str, status: T) -> Result<Response>
where
StatusCode: TryFrom<T>,
<StatusCode as TryFrom<T>>::Error: Into<http::Error>,
{
let response = Response::build()
.header(header::LOCATION, location)
.status(status)
.finish()?;
let status = response.status();
if !status.is_redirection() {
return Err(Error::new(format!(
"Invalid status code for redirect: {}",
status
)));
}
Ok(response)
}
}