index : static-web-server.git

ascending towards madness

author Jose Quintana <joseluisquintana20@gmail.com> 2021-05-04 22:28:47.0 +00:00:00
committer Jose Quintana <joseluisquintana20@gmail.com> 2021-05-04 22:28:47.0 +00:00:00
commit
069f7525de638207651dc9e4a19aa8ab2ea930c5 [patch]
tree
e5ebc063fd34b5d4cbda6c7e4dbf987fc8fabcac
parent
520e2204f70f7a7755ef35d2201d5c0e68c55e4a
download
069f7525de638207651dc9e4a19aa8ab2ea930c5.tar.gz

refactor: minor config usage on server module



Diff

 Cargo.lock    |  4 ++--
 src/config.rs |  9 ---------
 src/lib.rs    |  2 +-
 src/server.rs | 33 ++++++++++++++++-----------------
 4 files changed, 19 insertions(+), 29 deletions(-)

diff --git a/Cargo.lock b/Cargo.lock
index 4ccedc2..d8a5bc8 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -786,9 +786,9 @@ dependencies = [

[[package]]
name = "syn"
version = "1.0.71"
version = "1.0.72"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ad184cc9470f9117b2ac6817bfe297307418819ba40552f9b3846f05c33d5373"
checksum = "a1e8cdbefb79a9a5a65e0db8b47b723ee907b7c7f8496c76a1770b5c310bab82"
dependencies = [
 "proc-macro2",
 "quote",
diff --git a/src/config.rs b/src/config.rs
index ca29b26..5096d37 100644
--- a/src/config.rs
+++ b/src/config.rs
@@ -1,8 +1,5 @@
use once_cell::sync::OnceCell;
use structopt::StructOpt;

pub static CONFIG: OnceCell<Config> = OnceCell::new();

/// A blazing fast static files-serving web server powered by Rust
#[derive(Debug, StructOpt)]
pub struct Config {
@@ -71,9 +68,3 @@ pub struct Config {
    /// Specify the file path to read the private key.
    pub http2_tls_key: String,
}

impl Config {
    pub fn global() -> &'static Config {
        CONFIG.get().expect("Config is not initialized")
    }
}
diff --git a/src/lib.rs b/src/lib.rs
index dd10823..f80d600 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -16,6 +16,6 @@ pub mod static_files;
#[macro_use]
pub mod error;

pub use config::{Config, CONFIG};
pub use config::Config;
pub use error::*;
pub use server::Server;
diff --git a/src/server.rs b/src/server.rs
index a9c3fae..03a70b4 100644
--- a/src/server.rs
+++ b/src/server.rs
@@ -1,27 +1,26 @@
use hyper::server::Server as HyperServer;
use hyper::service::{make_service_fn, service_fn};
use std::net::{IpAddr, SocketAddr};
use std::sync::Arc;
use std::{
    net::{IpAddr, SocketAddr},
    sync::Arc,
};
use structopt::StructOpt;

use crate::{
    config::{Config, CONFIG},
    error_page,
};
use crate::{config::Config, error_page};
use crate::{error, helpers, logger, Result};
use crate::{handler, static_files::ArcPath};

/// Define a multi-thread HTTP or HTTP/2 web server.
pub struct Server {
    opts: Config,
    threads: usize,
}

impl Server {
    /// Create new multi-thread server instance.
    pub fn new() -> Self {
        // Initialize global config
        CONFIG.set(Config::from_args()).unwrap();
        let opts = Config::global();
    pub fn new() -> Server {
        // Get server config
        let opts = Config::from_args();

        // Configure number of worker threads
        let cpus = num_cpus::get();
@@ -30,15 +29,15 @@ impl Server {
            n => cpus * n,
        };

        Self { threads }
        Server { opts, threads }
    }

    /// Build and run the multi-thread `Server`.
    pub fn run(self) -> Result {
        tokio::runtime::Builder::new_multi_thread()
            .enable_all()
            .thread_name("static-web-server")
            .worker_threads(self.threads)
            .thread_name("static-web-server")
            .enable_all()
            .build()?
            .block_on(async {
                let r = self.start_server().await;
@@ -52,7 +51,7 @@ impl Server {

    /// Run the inner Hyper `HyperServer` forever on the current thread with the given configuration.
    async fn start_server(self) -> Result {
        let opts = Config::global();
        let opts = &self.opts;

        logger::init(&opts.log_level)?;

@@ -64,6 +63,7 @@ impl Server {

        // Check for a valid root directory
        let root_dir = helpers::get_valid_dirpath(&opts.root)?;
        let root_dir = ArcPath(Arc::new(root_dir));

        // Custom error pages content
        error_page::PAGE_404
@@ -82,8 +82,7 @@ impl Server {
            let span = tracing::info_span!("Server::run", ?addr, threads = ?self.threads);
            tracing::info!(parent: &span, "listening on http://{}", addr);

            let root_dir = ArcPath(Arc::new(root_dir));
            let create_service = make_service_fn(move |_| {
            let make_service = make_service_fn(move |_| {
                let root_dir = root_dir.clone();
                async move {
                    Ok::<_, error::Error>(service_fn(move |req| {
@@ -93,7 +92,7 @@ impl Server {
                }
            });

            HyperServer::bind(&addr).serve(create_service).await
            HyperServer::bind(&addr).serve(make_service).await
        });

        handle_signals();