diff options
author | Joris | 2024-06-02 14:38:13 +0200 |
---|---|---|
committer | Joris | 2024-06-02 14:38:22 +0200 |
commit | 1019ea1ed341e3a7769c046aa0be5764789360b6 (patch) | |
tree | 1a0d8a4f00cff252d661c42fc23ed4c19795da6f /src/main.rs | |
parent | e8da9790dc6d55cd2e8883322cdf9a7bf5b4f5b7 (diff) |
Migrate to Rust and Hyper
With sanic, downloading a file locally is around ten times slower than
with Rust and hyper.
Maybe `pypy` could have helped, but I didn’t succeed to set it up
quickly with the dependencies.
Diffstat (limited to 'src/main.rs')
-rw-r--r-- | src/main.rs | 68 |
1 files changed, 68 insertions, 0 deletions
diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..27da278 --- /dev/null +++ b/src/main.rs @@ -0,0 +1,68 @@ +use std::env; +use std::net::SocketAddr; + +use hyper::server::conn::http1; +use hyper::service::service_fn; +use hyper_util::rt::TokioIo; +use tokio::net::TcpListener; +use tokio_rusqlite::Connection; + +mod db; +mod model; +mod routes; +mod templates; +mod util; + +#[tokio::main] +async fn main() -> std::result::Result<(), Box<dyn std::error::Error>> { + env_logger::init(); + + let host = get_env("HOST"); + let port = get_env("PORT"); + let db_path = get_env("DB"); + let authorized_key = get_env("KEY"); + let files_dir = get_env("FILES_DIR"); + + let db_conn = Connection::open(db_path) + .await + .expect("Error while openning DB conection"); + + let addr: SocketAddr = format!("{host}:{port}") + .parse() + .unwrap_or_else(|_| panic!("Invalid address: {host}:{port}")); + + let listener = TcpListener::bind(addr).await?; + log::info!("Listening on http://{}", addr); + + loop { + let (stream, _) = listener.accept().await?; + let io = TokioIo::new(stream); + + let db_conn = db_conn.clone(); + let authorized_key = authorized_key.clone(); + let files_dir = files_dir.clone(); + + tokio::task::spawn(async move { + if let Err(err) = http1::Builder::new() + .serve_connection( + io, + service_fn(move |req| { + routes::routes( + req, + db_conn.clone(), + authorized_key.clone(), + files_dir.clone(), + ) + }), + ) + .await + { + log::error!("Failed to serve connection: {:?}", err); + } + }); + } +} + +fn get_env(key: &str) -> String { + env::var(key).unwrap_or_else(|_| panic!("Missing environment variable {key}")) +} |