SHARE
TWEET

Untitled

a guest Jan 19th, 2020 62 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. use std::io::prelude::*;
  2. use std::net::TcpListener;
  3. use std::net::TcpStream;
  4. use std::fs::File;
  5.  
  6. fn main() {
  7.     let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
  8.  
  9.     for stream in listener.incoming() {
  10.         let stream = stream.unwrap();
  11.  
  12.         handle_connection(stream);
  13.     }
  14. }
  15.  
  16. fn handle_connection(mut stream: TcpStream) {
  17.     let mut buffer = [0; 512];
  18.     stream.read(&mut buffer).unwrap();
  19.    
  20.     let get = b"GET / HTTP/1.1\r\n";
  21.  
  22.     let (status_line, filename) = if buffer.starts_with(get) {
  23.         ("HTTP/1.1 200 OK\r\n\n", "hello.html")
  24.     } else {
  25.         ("HTTP/1.1 404 NOT FOUND\r\n\n", "404.html")    
  26.     };
  27.  
  28.  
  29.     let mut file = File::open(filename).unwrap();
  30.     let mut contents = String::new();
  31.  
  32.     file.read_to_string(&mut contents).unwrap();
  33.  
  34.     let response = format!("{} {}", status_line, contents);
  35.  
  36.     stream.write(response.as_bytes()).unwrap();
  37.     stream.flush().unwrap();    
  38.    
  39. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Top