From 0144592cf399bd54f345f40aa9eeb1b47bbf8ebc Mon Sep 17 00:00:00 2001 From: core Date: Mon, 6 Jan 2025 14:07:06 -0500 Subject: [PATCH] xtask serve --- crates/xtask/src/main.rs | 42 ++++++++++++++++++++++++++++++++++------ 1 file changed, 36 insertions(+), 6 deletions(-) diff --git a/crates/xtask/src/main.rs b/crates/xtask/src/main.rs index be4059bd0e461cdf888697b685b75f22dbee2d51..9eec8055269851d03ec3b9cd66f08ae87794a5f1 100644 --- a/crates/xtask/src/main.rs +++ b/crates/xtask/src/main.rs @@ -1,17 +1,18 @@ use std::env::{args, var}; use std::error::Error; use std::fs; -use std::io::Read; +use std::io::{Cursor, Read}; use std::net::{SocketAddr, TcpListener, TcpStream}; use std::path::{Path, PathBuf}; use std::process::{Command, exit}; +use std::str::FromStr; use std::sync::mpsc; use std::sync::mpsc::TryRecvError; use std::thread::sleep; use std::time::Duration; use colored::Colorize; use notify::{Event, EventKind, RecursiveMode, Watcher}; -use tiny_http::Server; +use tiny_http::{Header, HeaderField, Response, Server, StatusCode}; use wasm_pack::command::build::{BuildOptions, Target}; use wasm_pack::command::run_wasm_pack; use wasm_pack::progressbar::LogLevel; @@ -69,7 +70,9 @@ fn try_build_client() -> bool { } fn start_server() { - let server = Server::http(var("BIND").unwrap_or("[::]:8000".to_string())).unwrap(); + let bind = var("BIND").unwrap_or("[::]:8000".to_string()); + let server = Server::http(&bind).unwrap(); + println!("{} on {bind}", "✓ Listening".magenta().bold()); for req in server.incoming_requests() { let mut path = Path::new(req.url()); if path == Path::new("/") { @@ -80,12 +83,39 @@ fn start_server() { let full_path = workspace_dir().join("crates/client").join(path); - let content = match fs::read(full_path) { + let content = match fs::read(full_path.clone()) { Ok(r) => r, - Err(_) => { continue; } + Err(_) => { + let _ = req.respond(Response::new(StatusCode::from(404), vec![], Cursor::new(vec![]), None, None)); + continue; + } }; + + let len = content.len(); + + let header = tiny_http::Header::from_bytes( + &b"Content-Type"[..], + if full_path.to_str().unwrap().ends_with(".html") { + &b"text/html"[..] + } else if full_path.to_str().unwrap().ends_with(".js") { + &b"text/javascript"[..] + } else if full_path.to_str().unwrap().ends_with(".wasm") { + &b"application/wasm"[..] + } else { + &b"application/octet-stream"[..] + } + ).unwrap(); - + let response = Response::new( + StatusCode::from(200), + vec![ + header + ], + Cursor::new(content), + Some(len), + None + ); + let _ = req.respond(response); } }