diff --git a/src/main.rs b/src/main.rs index 5ad2a79..33210a8 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,23 +1,25 @@ -use std::collections::HashMap; +use std::sync::LazyLock; use salvo::http::HeaderValue; use salvo::logging::Logger; use salvo::prelude::{ - affix_state, handler, Depot, Listener, Request, Response, Router, Server, Service, StaticDir, - TcpListener, + handler, Listener, Request, Response, Router, Server, Service, StaticDir, TcpListener, }; +use tokio::sync::Mutex; use crate::models::State; +static STORE: LazyLock> = LazyLock::new(State::new); + mod models; mod utility; #[handler] -async fn download(depot: &mut Depot, req: &mut Request, res: &mut Response) { +pub async fn download(req: &mut Request, res: &mut Response) { let article_id = req.param::("id").unwrap(); - let state = depot.obtain::().unwrap(); - let executable = state.executables.get(&article_id as &str).unwrap(); + let store = STORE.lock().await; + let executable = store.executables.get(&article_id as &str).unwrap(); let data = executable.with_key(b"test"); if let Err(e) = res.write_body(data) { @@ -41,17 +43,14 @@ async fn main() { let addr = format!("0.0.0.0:{}", port); tracing_subscriber::fmt().init(); - let mut state = State { - executables: HashMap::new(), - }; - - state.add_executable("windows", "./demo-windows.exe"); - state.add_executable("linux", "./demo-linux"); + let mut store = STORE.lock().await; + store.add_executable("windows", "./demo-windows.exe"); + store.add_executable("linux", "./demo-linux"); + drop(store); let static_dir = StaticDir::new(["./public"]).defaults("index.html"); let router = Router::new() - .hoop(affix_state::inject(state)) .push(Router::with_path("download/").get(download)) .push(Router::with_path("<**path>").get(static_dir)); diff --git a/src/models.rs b/src/models.rs index 6765cdf..f816751 100644 --- a/src/models.rs +++ b/src/models.rs @@ -1,4 +1,5 @@ use std::{collections::HashMap, path}; +use tokio::sync::Mutex; use crate::utility::search; @@ -8,6 +9,12 @@ pub(crate) struct State<'a> { } impl<'a> State<'a> { + pub(crate) fn new() -> Mutex { + Mutex::new(Self { + executables: HashMap::new(), + }) + } + pub(crate) fn add_executable(&mut self, exe_type: &'a str, exe_path: &str) { let data = std::fs::read(&exe_path).expect("Unable to read file");