Skip to content

Instantly share code, notes, and snippets.

@UltiRequiem
Created January 26, 2022 15:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save UltiRequiem/bf8caacb7b787e80796c2ec2688cb8a4 to your computer and use it in GitHub Desktop.
Save UltiRequiem/bf8caacb7b787e80796c2ec2688cb8a4 to your computer and use it in GitHub Desktop.
use colored::Colorize;
use open::that;
use std::{io::prelude::*, net};
// TODO: Manage Request asynchronously
pub async fn serve(app: &str, addr: &str, open_on_browser: bool) {
let listener = net::TcpListener::bind(&addr)
.unwrap_or_else(|e| panic!("Port {} is already used: {}", &addr, e));
let url = format!("http://{}", &addr);
println!("{}{}", "Listening on ".blue(), url.blue());
if open_on_browser {
that(url).unwrap_or_else(|e| {
eprintln!(
"Failed to open the component on your default browser: {}",
e
);
});
};
for stream in listener.incoming() {
let stream = stream.unwrap();
handle_connection(stream, &app);
}
}
fn handle_connection(mut stream: net::TcpStream, app: &str) {
match stream.read(&mut [0; 1024]) {
Ok(_) => println!("{}", "Request received.".green()),
Err(error) => panic!("Error reading the stream: {}", error),
};
let response = format!(
"HTTP/1.1 200 OK\r\nContent-Length: {}\r\n\r\n{}",
app.len(),
app
);
match stream.write(response.as_bytes()) {
Ok(_) => println!("[{}]", "Ping!".green()),
Err(error) => panic!("Could not write to stream: {}.", error),
};
stream.flush().unwrap();
}
use colored::Colorize;
use open::that;
use tokio::{
io::{AsyncReadExt, AsyncWriteExt},
net::TcpListener,
};
pub async fn serve(
app: &str,
addr: &str,
open_on_browser: bool,
) -> Result<(), Box<dyn std::error::Error>> {
let listener = TcpListener::bind(addr)
.await
.unwrap_or_else(|e| panic!("Port {} is already used: {}", addr, e));
let url = format!("http://{}", addr);
println!("{}{}", "Listening on ".blue(), url.blue());
if open_on_browser {
that(url)?
};
loop {
let (mut socket, _) = listener.accept().await?;
tokio::spawn(async move {
let mut buf = [0; 1024];
// In a loop, read data from the socket and write the data back.
loop {
let n = match socket.read(&mut buf).await {
// socket closed
Ok(n) if n == 0 => return,
Ok(n) => n,
Err(e) => {
eprintln!("failed to read from socket; err = {:?}", e);
return;
}
};
// Write the data back
if let Err(e) = socket.write_all(&buf[0..n]).await {
eprintln!("failed to write to socket; err = {:?}", e);
return;
}
}
});
}
}
@UltiRequiem
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment