aboutsummaryrefslogtreecommitdiff
path: root/src/main.rs
blob: 502f608fb9edcd5ed5ba8a26f87b309782c7f0ba (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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
use hyper::service::{make_service_fn, service_fn};
use hyper::Server;
use sqlx::sqlite::SqlitePool;
use std::convert::Infallible;
use std::net::SocketAddr;
use structopt::StructOpt;

#[macro_use]
extern crate log;

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

use model::config::Config;

#[derive(StructOpt)]
#[structopt()]
struct Opt {
    #[structopt(short, long, default_value = "127.0.0.1:3000")]
    address: SocketAddr,

    #[structopt(short, long, default_value = "config.json")]
    config: String,

    #[structopt(short, long, default_value = "database.db")]
    database: String,
}

#[tokio::main]
async fn main() {
    env_logger::Builder::from_env(
        env_logger::Env::default().default_filter_or("warn"),
    )
    .init();

    let opt = Opt::from_args();

    let config_str = std::fs::read_to_string(&opt.config)
        .expect(&format!("Missing {}", opt.config));
    let config: Config = serde_json::from_str(&config_str).unwrap();

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

    let assets = assets::get();

    let templates = templates::get();

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

    let make_svc = make_service_fn(|_conn| {
        let config = config.clone();
        let pool = pool.clone();
        let assets = assets.clone();
        let templates = templates.clone();
        async move {
            Ok::<_, Infallible>(service_fn(move |req| {
                routes::routes(
                    config.clone(),
                    pool.clone(),
                    assets.clone(),
                    templates.clone(),
                    req,
                )
            }))
        }
    });

    info!("Starting server at {}", opt.address);
    if let Err(e) = Server::bind(&opt.address).serve(make_svc).await {
        error!("server error: {}", e);
    }
}