added a builder pattern to CorsOptions (#75)

* added a builder pattern to CorsOptions

* builder pattern in corsOptions is now consuming
This commit is contained in:
morbatex 2020-01-22 02:42:16 +01:00 committed by Yong Wen Chua
parent f9603e118f
commit 51539453d5
1 changed files with 66 additions and 0 deletions

View File

@ -1152,6 +1152,60 @@ impl CorsOptions {
pub fn to_cors(&self) -> Result<Cors, Error> { pub fn to_cors(&self) -> Result<Cors, Error> {
Cors::from_options(self) Cors::from_options(self)
} }
/// Sets the allowed origins
pub fn allowed_origins(mut self, allowed_origins: AllowedOrigins) -> Self {
self.allowed_origins = allowed_origins;
self
}
/// Sets the allowed methodes
pub fn allowed_methods(mut self, allowed_methods: AllowedMethods) -> Self {
self.allowed_methods = allowed_methods;
self
}
/// Sets the allowed headers
pub fn allowed_headers(mut self, allowed_headers: AllowedHeaders) -> Self {
self.allowed_headers = allowed_headers;
self
}
/// Marks if credentials are allowed
pub fn allow_credentials(mut self, allow_credentials: bool) -> Self {
self.allow_credentials = allow_credentials;
self
}
/// Sets the expose headers
pub fn expose_headers(mut self, expose_headers: HashSet<String>) -> Self {
self.expose_headers = expose_headers;
self
}
/// Sets the max age
pub fn max_age(mut self, max_age: Option<usize>) -> Self {
self.max_age = max_age;
self
}
/// Marks if wildcards are send
pub fn send_wildcard(mut self, send_wildcard: bool) -> Self {
self.send_wildcard = send_wildcard;
self
}
/// Sets the base of the fairing route
pub fn fairing_route_base<S: Into<String>>(mut self, fairing_route_base: S) -> Self {
self.fairing_route_base = fairing_route_base.into();
self
}
/// Sets the rank of the fairing route
pub fn fairing_route_rank(mut self, fairing_route_rank: isize) -> Self {
self.fairing_route_rank = fairing_route_rank;
self
}
} }
/// Response generator and [Fairing](https://rocket.rs/guide/fairings/) for CORS /// Response generator and [Fairing](https://rocket.rs/guide/fairings/) for CORS
@ -2025,6 +2079,18 @@ mod tests {
cors.validate().unwrap(); cors.validate().unwrap();
} }
#[test]
fn cors_options_from_builder_pattern() {
let allowed_origins = AllowedOrigins::some_exact(&["https://www.acme.com"]);
let cors_options_from_builder = CorsOptions::default()
.allowed_origins(allowed_origins)
.allowed_methods(vec![http::Method::Get].into_iter().map(From::from).collect())
.allowed_headers(AllowedHeaders::some(&[&"Authorization", "Accept"]))
.allow_credentials(true)
.expose_headers(["Content-Type", "X-Custom"].iter().map(|s| (*s).to_string()).collect());
assert_eq!(cors_options_from_builder, make_cors_options());
}
/// Check that the the default deserialization matches the one returned by `Default::default` /// Check that the the default deserialization matches the one returned by `Default::default`
#[cfg(feature = "serialization")] #[cfg(feature = "serialization")]
#[test] #[test]