feat: implement CORS support with configuration options and middleware integration
This commit is contained in:
@@ -4,6 +4,7 @@ pub(crate) const LOGGING_UTC_KEY: &str = "LOGGING.UTC";
|
||||
pub(crate) const SERVER_ADDRESS_KEY: &str = "SERVER.ADDRESS";
|
||||
pub(crate) const SERVER_PORT_KEY: &str = "SERVER.PORT";
|
||||
pub(crate) const SERVER_SERVE_OPENAPI_KEY: &str = "SERVER.SERVE_OPENAPI";
|
||||
pub(crate) const SERVER_CORS_ALLOWED_ORIGINS_KEY: &str = "SERVER.CORS.ALLOWED_ORIGINS";
|
||||
//
|
||||
pub(crate) const DATABASE_URL_KEY: &str = "DATABASE.URL";
|
||||
pub(crate) const DATABASE_MAX_CONNECTIONS_KEY: &str = "DATABASE.MAX_CONNECTIONS";
|
||||
|
||||
@@ -3,7 +3,7 @@ use std::net::IpAddr;
|
||||
use config::{Config, ConfigError};
|
||||
use tracing::warn;
|
||||
|
||||
use crate::configs::key::SERVER_SERVE_OPENAPI_KEY;
|
||||
use crate::configs::key::{SERVER_CORS_ALLOWED_ORIGINS_KEY, SERVER_SERVE_OPENAPI_KEY};
|
||||
|
||||
use super::{
|
||||
FromConfig,
|
||||
@@ -15,6 +15,12 @@ pub struct ServerSettings {
|
||||
pub address: IpAddr,
|
||||
pub port: u16,
|
||||
pub serve_openapi: bool,
|
||||
pub cors: CORSSettings,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct CORSSettings {
|
||||
pub allowed_origins: Vec<String>,
|
||||
}
|
||||
|
||||
impl FromConfig for ServerSettings {
|
||||
@@ -57,6 +63,24 @@ impl FromConfig for ServerSettings {
|
||||
);
|
||||
DEFAULT_SERVE_OPENAPI
|
||||
}),
|
||||
|
||||
cors: CORSSettings {
|
||||
allowed_origins: _config
|
||||
.get_array(SERVER_CORS_ALLOWED_ORIGINS_KEY)
|
||||
.unwrap_or_else(|_| vec![])
|
||||
.into_iter()
|
||||
.filter_map(|val| match val.into_string() {
|
||||
Ok(s) => Some(s),
|
||||
Err(e) => {
|
||||
warn!(
|
||||
"Invalid origin in {} configuration: {}",
|
||||
SERVER_CORS_ALLOWED_ORIGINS_KEY, e
|
||||
);
|
||||
None
|
||||
}
|
||||
})
|
||||
.collect(),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user