feat(api): config from env vars (HOST, PORT, CORS_ALLOWED_ORIGINS, DATABASE_URL)
This commit is contained in:
52
crates/api/src/config.rs
Normal file
52
crates/api/src/config.rs
Normal file
@@ -0,0 +1,52 @@
|
||||
use std::env;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Config {
|
||||
pub database_url: String,
|
||||
pub host: String,
|
||||
pub port: u16,
|
||||
/// Parsed CORS origin policy
|
||||
pub cors_origins: CorsOrigins,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum CorsOrigins {
|
||||
/// Allow any origin (`CORS_ALLOWED_ORIGINS=*`)
|
||||
Any,
|
||||
/// Allow specific origins (`CORS_ALLOWED_ORIGINS=https://a.com,https://b.com`)
|
||||
List(Vec<String>),
|
||||
}
|
||||
|
||||
impl Config {
|
||||
pub fn from_env() -> Self {
|
||||
let database_url = env::var("DATABASE_URL")
|
||||
.unwrap_or_else(|_| "sqlite://./pocket-chords.db".into());
|
||||
|
||||
let host = env::var("HOST").unwrap_or_else(|_| "0.0.0.0".into());
|
||||
|
||||
let port = env::var("PORT")
|
||||
.ok()
|
||||
.and_then(|v| v.parse::<u16>().ok())
|
||||
.unwrap_or(8000);
|
||||
|
||||
let cors_origins = match env::var("CORS_ALLOWED_ORIGINS")
|
||||
.unwrap_or_else(|_| "*".into())
|
||||
.trim()
|
||||
.to_string()
|
||||
{
|
||||
s if s == "*" => CorsOrigins::Any,
|
||||
s => CorsOrigins::List(
|
||||
s.split(',')
|
||||
.map(|o| o.trim().to_string())
|
||||
.filter(|o| !o.is_empty())
|
||||
.collect(),
|
||||
),
|
||||
};
|
||||
|
||||
Self { database_url, host, port, cors_origins }
|
||||
}
|
||||
|
||||
pub fn bind_addr(&self) -> String {
|
||||
format!("{}:{}", self.host, self.port)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user