credence_lib/configuration/
redirect.rs

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