Simple HTTP Server

This commit is contained in:
GuilhermeWerner
2021-07-04 10:51:06 -03:00
parent b8b36dd68d
commit c342c61b1a
4 changed files with 72 additions and 1 deletions

14
Resources/404.html Normal file
View File

@ -0,0 +1,14 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Hello!</title>
</head>
<body>
<h1>Oops!</h1>
<p>Sorry, I don't know what you're asking for.</p>
</body>
</html>

14
Resources/Hello.html Normal file
View File

@ -0,0 +1,14 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Hello!</title>
</head>
<body>
<h1>Hello!</h1>
<p>Hi from Rust</p>
</body>
</html>

View File

@ -1,3 +1,44 @@
// Copyright (c) TribuFu. All Rights Reserved.
#![allow(non_snake_case)]
use std::fs;
use std::io::prelude::*;
use std::net::TcpListener;
use std::net::TcpStream;
#[doc(hidden)]
pub fn Main() {
let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
for stream in listener.incoming() {
let stream = stream.unwrap();
HandleConnection(stream);
}
}
fn HandleConnection(mut stream: TcpStream) {
let mut buffer = [0; 1024];
stream.read(&mut buffer).unwrap();
let get = b"GET / HTTP/1.1\r\n";
let (status_line, filename) = if buffer.starts_with(get) {
("HTTP/1.1 200 OK", "Hello.html")
} else {
("HTTP/1.1 404 NOT FOUND", "404.html")
};
let contents = fs::read_to_string(format!("Resources/{}", filename)).unwrap();
let response = format!(
"{}\r\nContent-Length: {}\r\n\r\n{}",
status_line,
contents.len(),
contents,
);
stream.write(response.as_bytes()).unwrap();
stream.flush().unwrap();
}

View File

@ -2,4 +2,6 @@
#![allow(non_snake_case)]
fn main() {}
fn main() {
Http::Main();
}