Implements CORS

This commit is contained in:
2024-02-26 02:01:05 -03:00
parent 1bf44a0c07
commit d98e1de8c1
8 changed files with 50 additions and 12 deletions

View File

@@ -1,4 +1,6 @@
use axum::Router;
use http::Method;
use tower_http::cors::{AllowOrigin, CorsLayer};
pub struct RouterBuilder {
router: Router,
@@ -16,6 +18,17 @@ impl RouterBuilder {
return self;
}
pub fn add_cors(&mut self, allowed_origins: Option<Vec<String>>) -> &mut Self {
let cors = CorsLayer::new()
.allow_methods([Method::GET, Method::POST, Method::OPTIONS])
.allow_origin(allowed_origins.map_or(AllowOrigin::any(), |origins| {
AllowOrigin::list(origins.iter().map(|s| s.parse().unwrap()))
}));
self.router = self.router.clone().layer(cors);
return self;
}
pub fn build(&self) -> Router {
self.router.clone()
}