diff options
| author | Santo Cariotti <santo@dcariotti.me> | 2022-09-12 13:30:19 +0000 |
|---|---|---|
| committer | Santo Cariotti <santo@dcariotti.me> | 2022-09-12 13:30:19 +0000 |
| commit | af3f5430a0b0f1834228b28fd89848959512e718 (patch) | |
| tree | 27e843c147b92bf09893012f323ddaf54f5eb0a5 /src | |
| parent | 385102a5763f667d53a9d8ed2052ccb8c791bc91 (diff) | |
Use configuration for environment variables
Diffstat (limited to 'src')
| -rw-r--r-- | src/config.rs | 38 | ||||
| -rw-r--r-- | src/db.rs | 3 | ||||
| -rw-r--r-- | src/files.rs | 8 | ||||
| -rw-r--r-- | src/logger.rs | 3 | ||||
| -rw-r--r-- | src/main.rs | 19 | ||||
| -rw-r--r-- | src/models/auth.rs | 2 | ||||
| -rw-r--r-- | src/models/model.rs | 6 | ||||
| -rw-r--r-- | src/models/user.rs | 6 | ||||
| -rw-r--r-- | src/routes/model.rs | 3 |
9 files changed, 61 insertions, 27 deletions
diff --git a/src/config.rs b/src/config.rs index 02ae63d..7e67214 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1,6 +1,34 @@ -// TODO: Everything here must be a std::env +pub use config::ConfigError; +use lazy_static::lazy_static; +use serde::Deserialize; -pub static PAGE_LIMIT: i64 = 20; -pub const MAX_UPLOAD_FILE_SIZE: u64 = 1024 * 1024; // 1 MB -pub const SAVE_FILE_BASE_PATH: &str = "./uploads"; -pub const UPLOADS_ENDPOINT: &str = "/uploads"; +// pub static PAGE_LIMIT: i64 = std::env::var("PAGE_LIMIT") +// .unwrap_or_else(|_| "20".to_string()) +// .parse::<i64>() +// .unwrap(); +// pub const MAX_UPLOAD_FILE_SIZE: u64 = 1024 * 1024; // 1 MB +// pub const SAVE_FILE_BASE_PATH: &str = &std::env::var("SAVE_FILE_BASE_PATH").unwrap(); +// pub const UPLOADS_ENDPOINT: &str = &std::env::var("UPLOADS_ENDPOINT").unwrap(); + +#[derive(Deserialize)] +pub struct Configuration { + pub page_limit: i64, + pub save_file_base_path: String, + pub uploads_endpoint: String, + pub rust_log: String, + pub database_url: String, + pub jwt_secret: String, + pub allowed_host: String, +} + +impl Configuration { + pub fn new() -> Result<Self, ConfigError> { + let mut cfg = config::Config::new(); + cfg.merge(config::Environment::default())?; + cfg.try_into() + } +} + +lazy_static! { + pub static ref CONFIG: Configuration = Configuration::new().expect("Config can be loaded"); +} @@ -9,8 +9,7 @@ static mut CONNECTION: Option<PgPool> = None; /// Setup database connection. Get variable `DATABASE_URL` from the environment. Sqlx crate already /// defines an error for environments without DATABASE_URL. pub async fn setup() -> Result<(), AppError> { - let database_url = - std::env::var("DATABASE_URL").expect("Define `DATABASE_URL` environment variable."); + let database_url = &crate::config::CONFIG.database_url; unsafe { CONNECTION = Some(PgPool::connect(&database_url).await?); diff --git a/src/files.rs b/src/files.rs index 616a75d..73e0497 100644 --- a/src/files.rs +++ b/src/files.rs @@ -1,4 +1,4 @@ -use crate::config::{SAVE_FILE_BASE_PATH, UPLOADS_ENDPOINT}; +use crate::config::CONFIG; use crate::errors::AppError; use axum::{ extract::{Multipart, Path}, @@ -30,8 +30,8 @@ pub async fn upload( { let rnd = (random::<f32>() * 1000000000 as f32) as i32; - let save_filename = format!("{}/{}.{}", SAVE_FILE_BASE_PATH, rnd, ext_name); - uploaded_file = format!("{}/{}.{}", UPLOADS_ENDPOINT, rnd, ext_name); + let save_filename = format!("{}/{}.{}", CONFIG.save_file_base_path, rnd, ext_name); + uploaded_file = format!("{}/{}.{}", CONFIG.uploads_endpoint, rnd, ext_name); let data = file.bytes().await.unwrap(); @@ -70,6 +70,6 @@ pub async fn show_uploads(Path(id): Path<String>) -> (HeaderMap, Vec<u8>) { HeaderValue::from_str(&content_type).unwrap(), ); } - let file_name = format!("{}/{}", SAVE_FILE_BASE_PATH, id); + let file_name = format!("{}/{}", CONFIG.save_file_base_path, id); (headers, read(&file_name).unwrap()) } diff --git a/src/logger.rs b/src/logger.rs index 151803f..3f3ff0f 100644 --- a/src/logger.rs +++ b/src/logger.rs @@ -4,8 +4,7 @@ use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt}; pub fn setup() { tracing_subscriber::registry() .with(tracing_subscriber::EnvFilter::new( - std::env::var("RUST_LOG") - .unwrap_or_else(|_| "verden=debug,tower_http=debug".into()), + crate::config::CONFIG.rust_log.clone(), )) .with(tracing_subscriber::fmt::layer()) .init(); diff --git a/src/main.rs b/src/main.rs index c20f667..39c6738 100644 --- a/src/main.rs +++ b/src/main.rs @@ -7,13 +7,14 @@ mod models; mod pagination; mod routes; -use crate::config::UPLOADS_ENDPOINT; +use crate::config::CONFIG; use axum::{ handler::Handler, http::{header, Request}, routing::get, Router, }; +use std::net::{SocketAddr, ToSocketAddrs}; use std::time::Duration; use tower_http::sensitive_headers::SetSensitiveHeadersLayer; use tower_http::{classify::ServerErrorsFailureClass, trace::TraceLayer}; @@ -24,11 +25,19 @@ use tracing::Span; async fn main() { let app = create_app().await; - // By default the server is bind at "127.0.0.1:3000" - let addr = std::env::var("ALLOWED_HOST").unwrap_or_else(|_| "127.0.0.1:3000".to_string()); + let host = &CONFIG.allowed_host; + let addr = match host.parse::<SocketAddr>() { + Ok(addr) => addr, + Err(_) => match host.to_socket_addrs() { + Ok(mut addr) => addr.next().unwrap(), + Err(e) => { + panic!("{}", e); + } + }, + }; tracing::info!("Listening on {}", addr); - axum::Server::bind(&addr.parse().unwrap()) + axum::Server::bind(&addr) .serve(app.into_make_service()) .await .unwrap(); @@ -46,7 +55,7 @@ async fn create_app() -> Router { Router::new() .route( - &format!("{}/:id", UPLOADS_ENDPOINT), + &format!("{}/:id", CONFIG.uploads_endpoint), get(crate::files::show_uploads), ) // Map all routes to `/v1/*` namespace diff --git a/src/models/auth.rs b/src/models/auth.rs index 36a0175..8a70244 100644 --- a/src/models/auth.rs +++ b/src/models/auth.rs @@ -40,7 +40,7 @@ pub struct LoginCredentials { } static KEYS: Lazy<Keys> = Lazy::new(|| { - let secret = std::env::var("JWT_SECRET").expect("JWT_SECRET must be set"); + let secret = &crate::config::CONFIG.jwt_secret; Keys::new(secret.as_bytes()) }); diff --git a/src/models/model.rs b/src/models/model.rs index 5b47f5c..f686192 100644 --- a/src/models/model.rs +++ b/src/models/model.rs @@ -1,4 +1,4 @@ -use crate::config::PAGE_LIMIT; +use crate::config::CONFIG; use crate::db::get_client; use crate::errors::AppError; @@ -163,8 +163,8 @@ impl Model { GROUP BY models.id, users.id LIMIT $1 OFFSET $2 "#, - PAGE_LIMIT, - PAGE_LIMIT * page + CONFIG.page_limit, + CONFIG.page_limit * page ) .fetch_all(pool) .await?; diff --git a/src/models/user.rs b/src/models/user.rs index 22bd130..55abc97 100644 --- a/src/models/user.rs +++ b/src/models/user.rs @@ -1,4 +1,4 @@ -use crate::config::PAGE_LIMIT; +use crate::config::CONFIG; use crate::db::get_client; use crate::errors::AppError; @@ -121,8 +121,8 @@ impl User { r#"SELECT id, email, username, is_staff FROM users LIMIT $1 OFFSET $2 "#, - PAGE_LIMIT, - PAGE_LIMIT * page + CONFIG.page_limit, + CONFIG.page_limit * page ) .fetch_all(pool) .await?; diff --git a/src/routes/model.rs b/src/routes/model.rs index d1ac197..34e896d 100644 --- a/src/routes/model.rs +++ b/src/routes/model.rs @@ -1,4 +1,3 @@ -use crate::config::MAX_UPLOAD_FILE_SIZE; use crate::errors::AppError; use crate::files::upload; use crate::models::{ @@ -69,7 +68,7 @@ async fn get_model(Path(model_id): Path<i32>) -> Result<Json<ModelUser>, AppErro async fn upload_model_file( claims: Claims, Path(model_id): Path<i32>, - ContentLengthLimit(multipart): ContentLengthLimit<Multipart, { MAX_UPLOAD_FILE_SIZE }>, + ContentLengthLimit(multipart): ContentLengthLimit<Multipart, { 1024 * 1024 }>, ) -> Result<Json<ModelUpload>, AppError> { let model = match Model::find_by_id(model_id).await { Ok(model) => model, |
