pax_compiler/design_server/
static_server.rs

1use crate::helpers::PAX_BADGE;
2use actix_web::middleware::Logger;
3use actix_web::{App, HttpServer};
4use colored::Colorize;
5use env_logger;
6use std::io::Write;
7use std::net::TcpListener;
8use std::path::PathBuf;
9
10pub fn start_server(fs_path: PathBuf) -> std::io::Result<()> {
11    // Initialize logging
12    std::env::set_var("RUST_LOG", "actix_web=info");
13    env_logger::Builder::from_env(env_logger::Env::default())
14        .format(|buf, record| writeln!(buf, "{} 🍱 Served {}", *PAX_BADGE, record.args()))
15        .init();
16
17    // Create a Runtime
18    let runtime = actix_web::rt::System::new().block_on(async {
19        let mut port = 8080;
20        let server = loop {
21            // Check if the port is available
22            if TcpListener::bind(("127.0.0.1", port)).is_ok() {
23                // Log the server details
24                println!(
25                    "{} 🗂️  Serving static files from {}",
26                    *PAX_BADGE,
27                    &fs_path.to_str().unwrap()
28                );
29                let address_msg = format!("http://127.0.0.1:{}", port).blue();
30                let server_running_at_msg = format!("Server running at {}", address_msg).bold();
31                println!("{} 📠 {}", *PAX_BADGE, server_running_at_msg);
32                break HttpServer::new(move || {
33                    App::new().wrap(Logger::new("| %s | %U")).service(
34                        actix_files::Files::new("/*", fs_path.clone()).index_file("index.html"),
35                    )
36                })
37                .bind(("127.0.0.1", port))
38                .expect("Error binding to address")
39                .workers(2);
40            } else {
41                port += 1; // Try the next port
42            }
43        };
44
45        server.run().await
46    });
47
48    runtime
49}