summaryrefslogtreecommitdiff
path: root/src/main.rs
blob: 74175c145532dc8a837abb3abd86069a82003bab (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
use serde::Deserialize;
use std::path::{Path, PathBuf};
use structopt::StructOpt;
use warp::Filter;
#[macro_use]
extern crate log;

#[derive(Debug, Deserialize)]
struct Config {
    webroot: PathBuf,
    port: u16,
    tls_key: PathBuf,
    tls_cert: PathBuf,
}

#[derive(Debug, StructOpt)]
#[structopt(name = "ewww", about = "Web server for static sites")]
struct Opt {
    #[structopt(parse(from_os_str))]
    config: PathBuf,
}

#[derive(Debug, thiserror::Error)]
enum EwwwError {
    #[error("Web root {0} does not exist")]
    WebrootNotFound(PathBuf),

    #[error("TLS certificate {0} does not exist")]
    TlsCertNotFound(PathBuf),

    #[error("TLS key {0} does not exist")]
    TlsKeyNotFound(PathBuf),
}

#[tokio::main]
async fn main() {
    pretty_env_logger::init();
    info!("ewww starting up");

    let opt = Opt::from_args();
    let config = read_config(&opt.config).unwrap();

    let webroot = config.webroot.canonicalize().unwrap();
    info!("webroot: {:?}", webroot);
    let log = warp::log("ewww");
    let webroot = warp::any().and(warp::fs::dir(webroot)).with(log);

    warp::serve(webroot)
        .tls()
        .key_path(config.tls_key)
        .cert_path(config.tls_cert)
        .run(([127, 0, 0, 1], config.port))
        .await;
}

fn read_config(filename: &Path) -> anyhow::Result<Config> {
    debug!("reading config from {:?}", filename);
    let config = std::fs::read_to_string(filename)?;
    let config: Config = serde_yaml::from_str(&config)?;
    check_config(&config)?;
    info!("config: {:?}", config);
    Ok(config)
}

fn check_config(config: &Config) -> anyhow::Result<()> {
    if !config.webroot.exists() {
        return Err(EwwwError::WebrootNotFound(config.webroot.clone()).into());
    }
    if !config.tls_cert.exists() {
        return Err(EwwwError::TlsCertNotFound(config.tls_cert.clone()).into());
    }
    if !config.tls_key.exists() {
        return Err(EwwwError::TlsKeyNotFound(config.tls_key.clone()).into());
    }
    Ok(())
}