Browse Source

Use is_dir instead of terminal slash

master
Noelle 4 years ago
parent
commit
566bcdb29f
1 changed files with 49 additions and 11 deletions
  1. 49
    11
      src/main.rs

+ 49
- 11
src/main.rs View File

@@ -11,6 +11,11 @@ use hello::ThreadPool;
extern crate regex;
use regex::Regex;

struct Response {
header: String,
path: String,
}

fn main() {
let listener = TcpListener::bind("127.0.0.1:26382").unwrap();
let pool = ThreadPool::new(4);
@@ -34,31 +39,64 @@ fn handle_connection(mut stream: TcpStream) {
// let get = b"GET / HTTP/1.1\r\n";
// let sleep = b"GET /sleep HTTP/1.1\r\n";

let (status_line, filename) = if buffer.starts_with(b"GET") {
let mut r = Response{
header: String::from(""),
path: String::from(""),
};

if buffer.starts_with(b"GET") {

let caps = hdr.captures(bf);
match caps {
Some(cap) => {
let c = cap.get(1).unwrap().as_str();
// println!("Asked to fetch {}", c);
println!("Asked to fetch {}", c);
//assert!(Path::new(c).exists());
if c == "" {
("HTTP/1.1 200 OK\r\n\r\n", "index.html")
println!("Asked to send root!");
r.header.push_str("HTTP/1.1 200 OK\r\n\r\n");
r.path.push_str("index.html");
} else if Path::new(c).exists() {
("HTTP/1.1 200 OK\r\n\r\n", c)
if Path::new(c).is_dir() {
let mut cs = c.to_string();
if cs.chars().last().unwrap().to_string() != "/" {
cs.push_str("/");
}
cs.push_str("index.html");
if Path::new(&cs).exists() {
println!("Asked to send {}", &cs);
r.header.push_str("HTTP/1.1 200 OK\r\n\r\n");
r.path.push_str(&cs);
} else {
println!("Asked to send {} and I couldn't find it", &cs);
r.header.push_str("HTTP/1.1 404 NOT FOUND\r\n\r\n");
r.path.push_str("404.html");
}
} else {
println!("Asked to send {}", &c);
r.header.push_str("HTTP/1.1 200 OK\r\n\r\n");
r.path.push_str(c);
}
} else {
("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html")
println!("Asked to send {} and I could not find it", &c);
r.header.push_str("HTTP/1.1 404 NOT FOUND\r\n\r\n");
r.path.push_str("404.html");
}
},
None => {
("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html")
println!("This wasn't even a well-formed header");
r.header.push_str("HTTP/1.1 404 NOT FOUND\r\n\r\n");
r.path.push_str("404.html");
}
}
} else {
("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html")
};
let contents = fs::read_to_string(filename).unwrap();
let response = format!("{}{}", status_line, contents);
println!("It didn't start with GET!");
r.header.push_str("HTTP/1.1 404 NOT FOUND\r\n\r\n");
r.path.push_str("404.html");
}
// println!("Sending {}: {}", r.header, r.path);
let contents = fs::read_to_string(r.path).unwrap();
let response = format!("{}{}", r.header, contents);

stream.write(response.as_bytes()).unwrap();
stream.flush().unwrap();
@@ -66,4 +104,4 @@ fn handle_connection(mut stream: TcpStream) {


// println!("Request: {}", String::from_utf8_lossy(&buffer[..]));
}
}

Loading…
Cancel
Save