sword_layers/cors/
config.rs

1use crate::{DisplayConfig, utils::TimeConfig};
2use console::style;
3use serde::{Deserialize, Serialize};
4
5/// ### CORS Configuration
6/// Configuration for the CORS Layer
7/// This configuration allows you to control cross-origin resource sharing policies.
8#[derive(Clone, Debug, Deserialize, Serialize)]
9#[serde(default)]
10pub struct CorsConfig {
11    /// Boolean indicating if CORS is enabled.
12    pub enabled: bool,
13
14    /// A list of allowed origins for cross-origin requests.
15    #[serde(rename = "allow-origins")]
16    pub allow_origins: Option<Vec<String>>,
17
18    /// A list of allowed HTTP methods (e.g., "GET", "POST").
19    #[serde(rename = "allow-methods")]
20    pub allow_methods: Option<Vec<String>>,
21
22    /// A list of allowed HTTP headers.
23    #[serde(rename = "allow-headers")]
24    pub allow_headers: Option<Vec<String>>,
25
26    /// A boolean indicating if credentials are allowed in cross-origin requests.
27    #[serde(rename = "allow-credentials")]
28    pub allow_credentials: Option<bool>,
29
30    /// The maximum age in seconds for CORS preflight responses.
31    #[serde(rename = "max-age")]
32    pub max_age: Option<TimeConfig>,
33
34    /// Whether to display the configuration details.
35    pub display: bool,
36}
37
38impl DisplayConfig for CorsConfig {
39    fn display(&self) {
40        if !self.display {
41            return;
42        }
43
44        println!("\n{}", style("CORS Configuration:").bold());
45        println!("  ↳  Enabled: {}", self.enabled);
46
47        if let Some(origins) = &self.allow_origins {
48            println!("  ↳  Origins: {}", origins.join(", "));
49        }
50
51        if let Some(methods) = &self.allow_methods {
52            println!("  ↳  Methods: {}", methods.join(", "));
53        }
54
55        if let Some(headers) = &self.allow_headers {
56            println!("  ↳  Headers: {}", headers.join(", "));
57        }
58
59        let mut options = Vec::new();
60        if let Some(credentials) = self.allow_credentials {
61            options.push(format!("credentials: {}", credentials));
62        }
63        if let Some(max_age) = &self.max_age {
64            options.push(format!("max age: {}", max_age.raw));
65        }
66        if !options.is_empty() {
67            println!("  ↳  Options: {}", options.join(" - "));
68        }
69    }
70}
71
72impl Default for CorsConfig {
73    fn default() -> Self {
74        CorsConfig {
75            enabled: false,
76            allow_origins: None,
77            allow_methods: None,
78            allow_headers: None,
79            allow_credentials: None,
80            max_age: None,
81            display: false,
82        }
83    }
84}