Skip to content

Commit

Permalink
refactor: Use results
Browse files Browse the repository at this point in the history
Will properly handle them later.
  • Loading branch information
donovanglover committed Apr 7, 2024
1 parent 4905d86 commit 8dfd1d8
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 18 deletions.
4 changes: 3 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ fn main() {

fn start_server(ip: Ipv4Addr, port: u16) {
let running_ip = SocketAddrV4::new(ip, port);

notify(&format!("Starting server on {running_ip}..."), None);
server::start(running_ip);

let _ = server::start(running_ip);
}
46 changes: 29 additions & 17 deletions src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,18 @@ use std::thread;
use urlencoding::decode;

/// Simple HTTP server that opens files based on GET requests
pub fn start(address: SocketAddrV4) {
let listener = TcpListener::bind(address).unwrap();
pub fn start(address: SocketAddrV4) -> Result<(), std::io::Error> {
let listener = TcpListener::bind(address)?;

for stream in listener.incoming() {
let stream = stream.unwrap();

thread::spawn(|| {
handle_connection(stream);
});
for maybe_stream in listener.incoming() {
if let Ok(stream) = maybe_stream {
thread::spawn(|| {
handle_connection(stream);
});
}
}

Ok(())
}

/// Opens the given file and returns 200, otherwise 404
Expand All @@ -25,7 +27,9 @@ fn handle_connection(mut stream: TcpStream) {
let request_line: Vec<&str> = request_line.split(' ').collect();

if let Some(request) = request_line.get(1) {
out(stream, "HTTP/1.1 200 OK", &open(request));
if let Ok(response) = open(request) {
out(stream, "HTTP/1.1 200 OK", &response);
}
} else {
out(stream, "HTTP/1.1 404 NOT FOUND", "");
}
Expand All @@ -40,21 +44,29 @@ fn out(mut stream: TcpStream, status: &str, contents: &str) {
}

/// Open an executable in wine
fn open(request: &str) -> String {
let request = decode(request).unwrap();
fn open(request: &str) -> Result<String, &'static str> {
let Ok(request) = decode(request) else {
return Err("The request was invalid.")
};

println!("{}", request);

let split = request.split("//").collect::<Vec<_>>();

let Output { stdout, stderr, .. } = Command::new("wine")
let Ok(Output { stdout, stderr, .. }) = Command::new("wine")
.env("WINEPREFIX", split[1])
.arg(split[0])
.output()
.unwrap();
.output() else {
return Err("Error while trying to run the wine command.")
};

let Ok(stdout) = String::from_utf8(stdout) else {
return Err("The program returned invalid stdout.")
};

let stdout = String::from_utf8(stdout).unwrap();
let stderr = String::from_utf8(stderr).unwrap();
let Ok(stderr) = String::from_utf8(stderr) else {
return Err("The program returned invalid stderr.")
};

format!("stdout:\n{stdout}\nstderr:\n{stderr}")
Ok(format!("stdout:\n{stdout}\nstderr:\n{stderr}"))
}

0 comments on commit 8dfd1d8

Please sign in to comment.