Fix: now any directory or file can be viewed (if not exists, displays not found without crashing)

This commit is contained in:
g1n 2021-07-16 14:03:27 +00:00
parent d5b412aef8
commit 419b116f93
1 changed files with 26 additions and 4 deletions

View File

@ -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();