From 419b116f93b456cb85a41a1f60e0aa6a203728a2 Mon Sep 17 00:00:00 2001 From: g1n Date: Fri, 16 Jul 2021 14:03:27 +0000 Subject: [PATCH] Fix: now any directory or file can be viewed (if not exists, displays not found without crashing) --- src/main.rs | 30 ++++++++++++++++++++++++++---- 1 file changed, 26 insertions(+), 4 deletions(-) diff --git a/src/main.rs b/src/main.rs index e4592f6..62cc54e 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,4 +1,5 @@ use std::fs; +use std::path::Path; use std::io::prelude::*; use std::net::TcpListener; use std::net::TcpStream; @@ -81,10 +82,10 @@ fn handle_connection(mut stream: TcpStream) { let get = format!( "{} {} {}\r\n {}\r\n", host, _path, _post_len, _post); let get_bytes = get.as_bytes(); - let (status_line, _filename) = if _path == "/" { - ("2 text/gemini", format!(".{}index.gmi", _path)) + let status_line = if Path::new(&format!("{}{}", "/home/g1n/public_spartan", _path).to_string()).exists() { + "2 text/gemini" } else { - ("4 Not found", format!(".{}error.gmi", "/")) // TODO: fix Not Found behaviour + "4 Not found" }; //let filename = "index.gmi"; @@ -93,12 +94,33 @@ fn handle_connection(mut stream: TcpStream) { if _filename != "" { let _contents = fs::read_to_string(_filename).unwrap(); } else { */ - let _contents = fs::read_to_string(_filename).unwrap(); + let mut _contents = "".to_string(); + let full_path = format!("{}{}", "/home/g1n/public_spartan", _path); + let mut exists = Path::new(&format!("{}{}", "/home/g1n/public_spartan", _path).to_string()).exists(); + if exists { + if Path::new(&full_path).is_file(){ + _contents = fs::read_to_string(format!("{}{}", "/home/g1n/public_spartan", _path)).unwrap(); + } else { + exists = Path::new(&format!("{}{}/index.gmi", "/home/g1n/public_spartan", _path).to_string()).exists(); + if exists { + _contents = fs::read_to_string(format!("{}{}index.gmi", "/home/g1n/public_spartan", _path)).unwrap(); + } else { + let listing = fs::read_dir(full_path).unwrap(); + println!("listing!"); + for file in listing { + println!("{}\n", file.unwrap().path().display()); + } + } + } + } + // TODO: add listing for folders + let response = format!( "{}\r\n {}", status_line, _contents ); + println!("{}", response); stream.write(response.as_bytes()).unwrap(); stream.flush().unwrap();