tela/response/
redirect.rs1use bytes::Bytes;
2use http_body_util::Full;
3use hyper::{Method, Uri};
4
5use super::{Result, ToErrorResponse, ToResponse};
6
7pub struct Redirect<const CODE: u16 = 302>(pub String);
8
9impl<const CODE: u16> Redirect<CODE> {
10 pub fn to<T: Into<String>>(value: T) -> Self {
11 Redirect(Into::<String>::into(value))
12 }
13}
14
15impl<const CODE: u16> ToErrorResponse for Redirect<CODE> {
16 fn to_error_response(
17 self,
18 code: u16,
19 reason: String,
20 ) -> Result<hyper::Response<http_body_util::Full<bytes::Bytes>>> {
21 if ![301, 302, 303, 307, 308].contains(&code) {
22 Ok(hyper::Response::builder()
23 .status(302)
24 .header("Content-Type", "text/html")
25 .header("Location", self.0.to_string())
26 .header("Tela-Reason", reason)
27 .body(Full::new(Bytes::new()))
28 .unwrap())
29 } else {
30 Ok(hyper::Response::builder()
31 .status(code)
32 .header("Content-Type", "text/html")
33 .header("Tela-Reason", reason)
34 .header("Location", self.0.to_string())
35 .body(Full::new(Bytes::new()))
36 .unwrap())
37 }
38 }
39}
40
41impl<const CODE: u16> ToResponse for Redirect<CODE> {
42 fn to_response(
43 self,
44 _method: &Method,
45 _uri: &Uri,
46 _body: String,
47 ) -> Result<hyper::Response<http_body_util::Full<bytes::Bytes>>> {
48 if ![301, 302, 303, 307, 308].contains(&CODE) {
49 Ok(hyper::Response::builder()
50 .status(302)
51 .header("Content-Type", "text/html")
52 .header("Location", self.0.to_string())
53 .body(Full::new(Bytes::new()))
54 .unwrap())
55 } else {
56 Ok(hyper::Response::builder()
57 .status(CODE)
58 .header("Content-Type", "text/html")
59 .header("Location", self.0.to_string())
60 .body(Full::new(Bytes::new()))
61 .unwrap())
62 }
63 }
64}