use std::sync::Arc;
use http::HeaderName;
use http::Method;
use super::config::Config;
use super::config::CorsConfigError;
use super::origin::OriginMatcher;
use super::plugin::CorsPlugin;
#[must_use]
pub struct CorsBuilder(Config);
impl Default for CorsBuilder {
#[inline]
fn default() -> Self {
Self::new()
}
}
impl CorsBuilder {
#[inline]
pub fn new() -> Self {
Self(Config::default())
}
#[inline]
pub fn allow_origin(mut self, o: impl Into<String>) -> Self {
self.0.origins.push(o.into());
self
}
#[inline]
pub fn allow_methods(mut self, m: &[Method]) -> Self {
self.0.methods = m.to_vec();
self
}
#[inline]
pub fn allow_headers(mut self, h: &[HeaderName]) -> Self {
self.0.headers = h.to_vec();
self
}
#[inline]
pub fn allow_credentials(mut self, allow: bool) -> Self {
self.0.allow_credentials = allow;
self
}
#[inline]
pub fn max_age_secs(mut self, secs: u32) -> Self {
self.0.max_age_secs = Some(secs);
self
}
#[inline]
pub fn allow_origin_suffix(mut self, suffix: impl Into<String>) -> Self {
self
.0
.origin_matchers
.push(OriginMatcher::Suffix(suffix.into()));
self
}
#[inline]
pub fn allow_origin_predicate<F>(mut self, f: F) -> Self
where
F: Fn(&str) -> bool + Send + Sync + 'static,
{
self
.0
.origin_matchers
.push(OriginMatcher::Custom(Arc::new(f)));
self
}
#[inline]
pub fn allow_private_network(mut self, yes: bool) -> Self {
self.0.allow_private_network = yes;
self
}
#[inline]
pub fn build(self) -> CorsPlugin {
self.try_build().expect("invalid CORS configuration")
}
#[inline]
pub fn try_build(self) -> Result<CorsPlugin, CorsConfigError> {
self.0.validate()?;
Ok(CorsPlugin { cfg: self.0 })
}
}