credence_lib/configuration/
redirect.rs

1use super::super::resolve::*;
2
3use {
4    axum::http::*,
5    compris::resolve::*,
6    kutil::{cli::depict::*, std::immutable::*},
7    regex::*,
8};
9
10//
11// Redirect
12//
13
14/// Redirect.
15#[derive(Clone, Debug, Depict, Resolve)]
16pub struct Redirect {
17    /// Regex.
18    ///
19    /// See [implementation syntax](https://docs.rs/regex/latest/regex/#syntax).
20    #[resolve(required)]
21    #[depict(as(display), style(string))]
22    pub regex: ResolveRegex,
23
24    /// Expand to.
25    ///
26    /// See [implementation syntax](https://docs.rs/regex/latest/regex/struct.Captures.html#method.expand).
27    #[resolve(required, key = "to")]
28    #[depict(style(string))]
29    pub expand_to: ByteString,
30
31    /// Redirect status code. Defaults to 301 (Moved Permanently).
32    #[resolve(key = "code")]
33    #[depict(as(display), style(symbol))]
34    pub status_code: ResolveStatusCode,
35}
36
37impl Redirect {
38    /// If the URI is redirected returns the redirected URI.
39    pub fn redirect(&self, uri_path: &str) -> Option<(String, StatusCode)> {
40        if let Some(captures) = self.regex.inner.captures(uri_path) {
41            let mut uri_path = String::default();
42            captures.expand(&self.expand_to, &mut uri_path);
43            return Some((uri_path, self.status_code.inner));
44        }
45
46        None
47    }
48}
49
50impl Default for Redirect {
51    fn default() -> Self {
52        Self {
53            regex: Regex::new("").expect("regex").into(),
54            expand_to: Default::default(),
55            status_code: StatusCode::MOVED_PERMANENTLY.into(),
56        }
57    }
58}