Skip to main content

serverkit/
redirect.rs

1use crate::{IntoResponse, Response, openapi::Operation};
2
3pub struct Redirect {
4    status: u16,
5    location: String,
6}
7
8impl Redirect {
9    pub fn temporary(location: impl Into<String>) -> Self {
10        Self {
11            status: 307,
12            location: location.into(),
13        }
14    }
15
16    pub fn permanent(location: impl Into<String>) -> Self {
17        Self {
18            status: 308,
19            location: location.into(),
20        }
21    }
22
23    pub fn see_other(location: impl Into<String>) -> Self {
24        Self {
25            status: 303,
26            location: location.into(),
27        }
28    }
29
30    pub fn found(location: impl Into<String>) -> Self {
31        Self {
32            status: 302,
33            location: location.into(),
34        }
35    }
36}
37
38impl IntoResponse for Redirect {
39    fn into_response(self) -> Response {
40        let mut response = Response::new(self.status);
41
42        if let Err(error) = response.headers().set("Location", self.location) {
43            return error.into_response();
44        }
45
46        response
47    }
48
49    fn openapi(operation: &mut Operation) {
50        operation.response(307, "Redirect", None, None);
51    }
52}