aboutsummaryrefslogtreecommitdiff
path: root/src/main.rs
blob: c1e326845ac96058b9cf5d8e36651e8d7ff22bc4 (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
// 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::{CONFIG, HELP_TEXT};

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

    if CONFIG.help {
        println!("{}", HELP_TEXT);
        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(())
    })
}