aboutsummaryrefslogtreecommitdiff
path: root/src/main.rs
blob: 2b3aebd94db73d62098f92e5b2d0ceaaf015255b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
use hyper::server::conn::http1;
use hyper::service::service_fn;
use hyper_util::rt::TokioIo;
use sqlx::sqlite::SqlitePool;
use tokio::net::TcpListener;

mod assets;
mod controller;
mod crypto;
mod db;
mod jobs;
mod mail;
mod model;
mod payer;
mod queries;
mod routes;
mod templates;
mod utils;
mod validation;

use model::config;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {

    env_logger::init();

    let config = config::from_env()
        .unwrap_or_else(|err| panic!("Error reading config: {err}"));

    let pool = SqlitePool::connect(&format!("sqlite:{}", config.db_path))
        .await
        .unwrap();

    let assets = assets::get();

    let templates = templates::get();

    tokio::spawn(jobs::start(config.clone(), pool.clone(), templates.clone()));

    let listener = TcpListener::bind(config.socket_address).await?;
    log::info!("Starting server at {}", config.socket_address);

    loop {
        let config = config.clone();
        let pool = pool.clone();
        let assets = assets.clone();
        let templates = templates.clone();
        let (stream, _) = listener.accept().await?;

        let io = TokioIo::new(stream);

        tokio::task::spawn(async move {
            if let Err(err) = http1::Builder::new()
                .serve_connection(
                    io,
                    service_fn(move |req| {
                        routes::routes(
                            config.clone(),
                            pool.clone(),
                            assets.clone(),
                            templates.clone(),
                            req,
                        )
                    }),
                )
                .await
            {
                println!("Error serving connection: {:?}", err);
            }
        });
    }
}