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
|
use serde::Deserialize;
use std::net::{SocketAddr, ToSocketAddrs};
use std::path::{Path, PathBuf};
use structopt::StructOpt;
use warp::Filter;
#[macro_use]
extern crate log;
#[derive(Debug, Deserialize)]
struct Config {
webroot: PathBuf,
listen: String,
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)]
#[allow(clippy::enum_variant_names)]
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() -> anyhow::Result<()> {
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();
let addr: SocketAddr = config.listen.to_socket_addrs().unwrap().next().unwrap();
info!("webroot: {:?}", webroot);
info!("listen on {}", addr);
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(addr)
.await;
Ok(())
}
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(())
}
|