From fb981d64172a0da75927125c2a63bf88f1b72fc4 Mon Sep 17 00:00:00 2001 From: Dendy Faist Date: Tue, 24 Sep 2024 08:12:04 +0200 Subject: [PATCH] feat: True multithread & intial shared state --- Cargo.toml | 2 +- src/handlers.rs | 14 +++++++++++--- src/main.rs | 13 ++++++++----- 3 files changed, 20 insertions(+), 9 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index a81a722..7bc537a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -8,5 +8,5 @@ askama = "0.12.1" axum = "0.7.5" glob = "0.3.1" serde = { version = "1.0.210", features = ['derive'] } -tokio = "1.40.0" +tokio = { version = "1.40.0", features = [ 'rt-multi-thread' ] } toml = "0.8.19" diff --git a/src/handlers.rs b/src/handlers.rs index f202939..237db6d 100644 --- a/src/handlers.rs +++ b/src/handlers.rs @@ -1,11 +1,19 @@ +use std::sync::Arc; +use std::sync::RwLock; + use crate::templates::HtmlTemplate; use crate::templates::ListTemplate; -use crate::utils::find_files; +use crate::utils; +use axum::extract::State; use axum::response::IntoResponse; -pub async fn list_files(base_path: String) -> impl IntoResponse { +pub async fn list_files( + State(state): State>>>, +) -> impl IntoResponse { + let files = state.read().unwrap(); // Adquire lock + let template = ListTemplate { - files: find_files(&base_path).unwrap(), + files: files.to_vec(), }; HtmlTemplate(template) } diff --git a/src/main.rs b/src/main.rs index e597b7d..ee12ffc 100644 --- a/src/main.rs +++ b/src/main.rs @@ -3,20 +3,23 @@ mod handlers; mod templates; mod utils; +use std::sync::{Arc, RwLock}; + use crate::config::read_config; use crate::handlers::list_files; use axum::routing::get; use axum::Router; use tokio::net::TcpListener; -#[tokio::main(flavor = "current_thread")] +#[tokio::main] async fn main() { let config = read_config().expect("Failed to read config"); - let app = Router::new().route( - "/", - get(move || list_files(config.settings.base_directory.clone())), - ); + let files = Arc::new(RwLock::new( + utils::find_files(&config.settings.base_directory).expect("Couldn't open files directory"), + )); + + let app = Router::new().route("/", get(list_files)).with_state(files); let listener = TcpListener::bind("127.0.0.1:3004").await.unwrap();