~starkingdoms/starkingdoms

0144592cf399bd54f345f40aa9eeb1b47bbf8ebc — core 11 months ago 0fac9a1
xtask serve
1 files changed, 36 insertions(+), 6 deletions(-)

M crates/xtask/src/main.rs
M crates/xtask/src/main.rs => crates/xtask/src/main.rs +36 -6
@@ 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);
    }
}