You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

main.rs 1.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. use std::net::{TcpStream, TcpListener};
  2. use std::io::prelude::*;
  3. use std::fs;
  4. // use std::thread;
  5. // use std::time::Duration;
  6. // use std::str;
  7. use std::path::Path;
  8. use hello::ThreadPool;
  9. extern crate regex;
  10. use regex::Regex;
  11. fn main() {
  12. let listener = TcpListener::bind("127.0.0.1:26382").unwrap();
  13. let pool = ThreadPool::new(4);
  14. for stream in listener.incoming() {
  15. let stream = stream.unwrap();
  16. pool.execute(|| {
  17. handle_connection(stream);
  18. });
  19. }
  20. println!("Shutting down.");
  21. }
  22. fn handle_connection(mut stream: TcpStream) {
  23. let mut buffer = [0; 512];
  24. stream.read(&mut buffer).unwrap();
  25. let hdr = Regex::new(r"GET /([^ ]*) HTTP/1.1").unwrap();
  26. let bf = &String::from_utf8_lossy(&buffer[..]);
  27. // let get = b"GET / HTTP/1.1\r\n";
  28. // let sleep = b"GET /sleep HTTP/1.1\r\n";
  29. let (status_line, filename) = if buffer.starts_with(b"GET") {
  30. let caps = hdr.captures(bf);
  31. match caps {
  32. Some(cap) => {
  33. let c = cap.get(1).unwrap().as_str();
  34. // println!("Asked to fetch {}", c);
  35. //assert!(Path::new(c).exists());
  36. if c == "" {
  37. ("HTTP/1.1 200 OK\r\n\r\n", "index.html")
  38. } else if Path::new(c).exists() {
  39. ("HTTP/1.1 200 OK\r\n\r\n", c)
  40. } else {
  41. ("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html")
  42. }
  43. },
  44. None => {
  45. ("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html")
  46. }
  47. }
  48. } else {
  49. ("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html")
  50. };
  51. let contents = fs::read_to_string(filename).unwrap();
  52. let response = format!("{}{}", status_line, contents);
  53. stream.write(response.as_bytes()).unwrap();
  54. stream.flush().unwrap();
  55. // println!("Request: {}", String::from_utf8_lossy(&buffer[..]));
  56. }