refactor: minor code syntax and docs improvements
Diff
src/compression.rs | 2 +-
src/control_headers.rs | 4 ++--
src/error_page.rs | 8 ++++----
src/handler.rs | 23 +++++++++++------------
src/security_headers.rs | 2 +-
src/server.rs | 19 ++++++++++---------
src/signals.rs | 12 ++++++------
src/static_files.rs | 20 +++++++++++++-------
8 files changed, 48 insertions(+), 42 deletions(-)
@@ -15,7 +15,7 @@ use std::pin::Pin;
use std::task::{Context, Poll};
use tokio_util::io::{ReaderStream, StreamReader};
use crate::error::Result;
use crate::Result;
pub const TEXT_MIME_TYPES: [&str; 16] = [
@@ -1,5 +1,5 @@
use headers::{CacheControl, HeaderMapExt};
@@ -13,7 +13,7 @@ const CACHE_EXT_ONE_YEAR: [&str; 30] = [
];
pub fn with_cache_control(ext: &str, resp: &mut Response<Body>) {
pub fn append_headers(ext: &str, resp: &mut Response<Body>) {
let mut max_age = 60 * 60 * 24_u64;
@@ -2,16 +2,16 @@ use headers::{AcceptRanges, ContentLength, ContentType, HeaderMapExt};
use hyper::{Body, Method, Response, StatusCode};
use once_cell::sync::OnceCell;
use crate::error::Result;
use crate::Result;
pub static PAGE_404: OnceCell<String> = OnceCell::new();
pub static PAGE_50X: OnceCell<String> = OnceCell::new();
pub fn get_error_response(method: &Method, status_code: &StatusCode) -> Result<Response<Body>> {
pub fn error_response(method: &Method, status_code: &StatusCode) -> Result<Response<Body>> {
tracing::warn!(method = ?method, status = status_code.as_u16(), error = ?status_code.to_owned());
let mut error_page_content = String::new();
let status_code = match status_code {
@@ -57,7 +57,7 @@ pub fn get_error_response(method: &Method, status_code: &StatusCode) -> Result<R
| &StatusCode::VARIANT_ALSO_NEGOTIATES
| &StatusCode::INSUFFICIENT_STORAGE
| &StatusCode::LOOP_DETECTED => {
error_page_content = match PAGE_50X.get() {
Some(s) => s.to_owned(),
None => {
@@ -2,10 +2,10 @@ use http::StatusCode;
use hyper::{Body, Request, Response};
use std::{future::Future, path::PathBuf, sync::Arc};
use crate::{compression, control_headers, cors, security_headers, static_files};
use crate::{error_page, Error, Result};
use crate::{compression, control_headers, cors, error_page, security_headers, static_files};
use crate::{Error, Result};
pub struct RequestHandlerOpts {
pub root_dir: PathBuf,
pub compression: bool,
@@ -14,12 +14,13 @@ pub struct RequestHandlerOpts {
pub security_headers: bool,
}
pub struct RequestHandler {
pub opts: RequestHandlerOpts,
}
impl RequestHandler {
pub fn handle<'a>(
&'a self,
req: &'a mut Request<Body>,
@@ -41,19 +42,17 @@ impl RequestHandler {
}
Err(e) => {
tracing::debug!("cors error kind: {:?}", e);
return error_page::get_error_response(method, &StatusCode::FORBIDDEN);
return error_page::error_response(method, &StatusCode::FORBIDDEN);
}
};
}
match static_files::handle_request(method, headers, root_dir, uri_path, dir_listing)
.await
{
match static_files::handle(method, headers, root_dir, uri_path, dir_listing).await {
Ok(mut resp) => {
if self.opts.security_headers {
security_headers::with_security_headers(&mut resp);
security_headers::append_headers(&mut resp);
}
@@ -63,11 +62,11 @@ impl RequestHandler {
let ext = uri_path.to_lowercase();
control_headers::with_cache_control(&ext, &mut resp);
control_headers::append_headers(&ext, &mut resp);
Ok(resp)
}
Err(status) => error_page::get_error_response(method, &status),
Err(status) => error_page::error_response(method, &status),
}
}
}
@@ -6,7 +6,7 @@ use hyper::{Body, Response};
pub fn with_security_headers(resp: &mut Response<Body>) {
pub fn append_headers(resp: &mut Response<Body>) {
resp.headers_mut().insert(
STRICT_TRANSPORT_SECURITY,
@@ -6,8 +6,7 @@ use structopt::StructOpt;
use crate::handler::{RequestHandler, RequestHandlerOpts};
use crate::tls::{TlsAcceptor, TlsConfigBuilder};
use crate::Result;
use crate::{config::Config, service::RouterService};
use crate::{config::Config, service::RouterService, Result};
use crate::{cors, error_page, helpers, logger, signals};
@@ -49,14 +48,13 @@ impl Server {
Ok(())
}
async fn start_server(self) -> Result {
let opts = &self.opts;
logger::init(&opts.log_level)?;
tracing::info!("runtime worker threads: {}", self.threads);
let (tcplistener, addr_string);
match opts.fd {
Some(fd) => {
@@ -89,6 +87,10 @@ impl Server {
.set(helpers::read_file_content(opts.page50x.as_ref()))
.expect("page 50x is not initialized");
let threads = self.threads;
tracing::info!("runtime worker threads: {}", self.threads);
let security_headers = opts.security_headers;
tracing::info!("security headers: enabled={}", security_headers);
@@ -101,10 +103,7 @@ impl Server {
let dir_listing = opts.directory_listing;
tracing::info!("directory listing: enabled={}", dir_listing);
let threads = self.threads;
let cors = cors::new(opts.cors_allow_origins.trim().to_owned());
@@ -118,6 +117,8 @@ impl Server {
},
});
if opts.http2 {
@@ -3,19 +3,19 @@ use std::sync::mpsc::channel;
use crate::{Context, Result};
pub fn wait_for_ctrl_c() -> Result {
let (tx, rx) = channel();
ctrlc::set_handler(move || tx.send(()).expect("Could not send signal on channel."))
.with_context(|| "Error setting Ctrl-C handler.".to_owned())?;
ctrlc::set_handler(move || tx.send(()).expect("could not send signal on channel"))
.with_context(|| "error setting Ctrl-C handler".to_owned())?;
tracing::info!("Press Ctrl+C to shutdown server.");
tracing::info!("press Ctrl+C to shutdown server");
rx.recv()
.with_context(|| "Could not receive signal from channel.".to_owned())?;
.with_context(|| "could not receive signal from channel".to_owned())?;
tracing::warn!("Ctrl+C signal caught, shutting down server execution.");
tracing::warn!("Ctrl+C signal caught, shutting down server execution");
Ok(())
}
@@ -24,11 +24,11 @@ use tokio::fs::File as TkFile;
use tokio::io::AsyncSeekExt;
use tokio_util::io::poll_read_buf;
use crate::error::Result;
use crate::Result;
pub async fn handle_request(
pub async fn handle(
method: &Method,
headers: &HeaderMap<HeaderValue>,
base: &Path,
@@ -72,6 +72,8 @@ pub async fn handle_request(
file_reply(headers, (filepath, meta, auto_index)).await
}
fn path_from_tail(
base: PathBuf,
tail: &str,
@@ -96,6 +98,9 @@ fn path_from_tail(
})
}
fn directory_listing<'a>(
method: &'a Method,
current_path: &'a str,
@@ -103,10 +108,11 @@ fn directory_listing<'a>(
) -> impl Future<Output = Result<Response<Body>, StatusCode>> + Send + 'a {
let is_head = method == Method::HEAD;
let parent = filepath.parent().unwrap_or(filepath);
tokio::fs::read_dir(parent).then(move |res| match res {