aboutsummaryrefslogtreecommitdiff
path: root/src/main.rs
blob: 3bd25d50f1fff7f22c86f0d2b76938b9705b1410 (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
// extern
use anyhow::Result;
use hyper::service::{make_service_fn, service_fn};
use hyper::Server;
use log::trace;

// internal
mod db;
use db::{init_db, open_connection};

mod service;
use service::shortner_service;

mod cli;
use cli::{version, CONFIG, HELP_TEXT};

fn main() -> Result<()> {
    pretty_env_logger::init();

    if CONFIG.help {
        version();
        println!("{}", HELP_TEXT);
        return Ok(());
    }
    if CONFIG.version {
        version();
        return Ok(());
    }

    init_db(&CONFIG.db_path)?;
    smol::run(async {
        let addr = ([127, 0, 0, 1], CONFIG.port).into();
        let service = make_service_fn(|_| async {
            Ok::<_, hyper::Error>(service_fn(move |req| {
                let db_conn = open_connection(&CONFIG.db_path).unwrap();
                shortner_service(req, db_conn)
            }))
        });
        let server = Server::bind(&addr).serve(service);
        trace!("Listening on http://{}", addr);
        server.await.unwrap();
        Ok(())
    })
}