-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.rs
82 lines (77 loc) · 2.6 KB
/
main.rs
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
use std::process;
use std::process::exit;
use std::time::Duration;
use clap::{command, Parser};
use wruster::http;
use wruster::router;
use wruster::router::HttpHandler;
use wruster::{Certificate, PrivateKey, Server, Timeouts};
use wruster_handlers::{log_middleware, serve_static};
#[macro_use]
extern crate log;
#[derive(Parser, Debug)]
#[command(author = "manel montilla", version = "0.0.1")]
/// Static web server that exposes the files under a directory through HTTP.
struct Cli {
/// [IP|host]:port to listen.
addres: String,
/// Directory to serve.
directory: String,
/// Path to a private key file in pem format.
///
/// Indicates that the server must use the provided certificate to accept
/// connections using TLS.
#[arg(long, requires = "tls_cert")]
tls_private: Option<String>,
/// Path to a certificate file in pem format.
///
/// Indicates that the server must use the provided private key to accept
/// connections using TLS.
#[arg(long, requires = "tls_private")]
tls_cert: Option<String>,
}
fn main() {
env_logger::init();
let cli = Cli::parse();
let addr = cli.addres;
let dir = cli.directory;
let routes = router::Router::new();
let serve_dir: HttpHandler =
log_middleware(Box::new(move |request| serve_static(&dir, request)));
routes.add("/", http::HttpMethod::GET, serve_dir);
let timeouts = Timeouts {
write_response_timeout: Duration::from_secs(10),
read_request_timeout: Duration::from_secs(10),
};
let mut server = Server::from_timeouts(timeouts);
let running = match cli.tls_cert {
Some(cert) => {
let cert = Certificate::read_from(&cert)
.map_err(|err| {
error!("{}", err);
exit(1)
})
.unwrap();
// The spec ensures that if the tls_cert flag is the defined the
// tls_private must be also defined.
let private_key_file = cli.tls_private.unwrap();
let key = PrivateKey::read_from(&private_key_file)
.map_err(|err| {
error!("{}", err);
exit(1)
})
.unwrap();
server.run_tls(&addr, routes, key, cert)
}
None => server.run(&addr, routes),
};
if let Err(err) = running {
error!("error running wruster {}", err.to_string());
process::exit(1);
}
if let Err(err) = server.wait() {
error!("error running wruster {}", err.to_string());
process::exit(1);
};
process::exit(0);
}