123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107 |
- use std::net::{TcpStream, TcpListener};
- use std::io::prelude::*;
- use std::fs;
- // use std::thread;
- // use std::time::Duration;
- // use std::str;
- use std::path::Path;
-
- 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);
-
- for stream in listener.incoming() {
- let stream = stream.unwrap();
- pool.execute(|| {
- handle_connection(stream);
- });
- }
-
- println!("Shutting down.");
- }
-
- fn handle_connection(mut stream: TcpStream) {
- let mut buffer = [0; 512];
- stream.read(&mut buffer).unwrap();
-
- let hdr = Regex::new(r"GET /([^ ]*) HTTP/1.1").unwrap();
- let bf = &String::from_utf8_lossy(&buffer[..]);
- // let get = b"GET / HTTP/1.1\r\n";
- // let sleep = b"GET /sleep HTTP/1.1\r\n";
-
- 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);
- //assert!(Path::new(c).exists());
- if c == "" {
- 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() {
- 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 {
- 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 => {
- 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 {
- 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();
-
-
-
- // println!("Request: {}", String::from_utf8_lossy(&buffer[..]));
- }
|