feat: True multithread & intial shared state

This commit is contained in:
Dendy 2024-09-24 08:12:04 +02:00
parent 90c6839d5d
commit fb981d6417
3 changed files with 20 additions and 9 deletions

View File

@ -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"

View File

@ -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<Arc<RwLock<Vec<utils::FileEntry>>>>,
) -> impl IntoResponse {
let files = state.read().unwrap(); // Adquire lock
let template = ListTemplate {
files: find_files(&base_path).unwrap(),
files: files.to_vec(),
};
HtmlTemplate(template)
}

View File

@ -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();