From c342c61b1a471409e271b33039e684a67f2bffe5 Mon Sep 17 00:00:00 2001 From: GuilhermeWerner <26710260+GuilhermeWerner@users.noreply.github.com> Date: Sun, 4 Jul 2021 10:51:06 -0300 Subject: [PATCH] Simple HTTP Server --- Resources/404.html | 14 ++++++++++++++ Resources/Hello.html | 14 ++++++++++++++ Source/Http.rs | 41 +++++++++++++++++++++++++++++++++++++++++ Source/Main.rs | 4 +++- 4 files changed, 72 insertions(+), 1 deletion(-) create mode 100644 Resources/404.html create mode 100644 Resources/Hello.html diff --git a/Resources/404.html b/Resources/404.html new file mode 100644 index 0000000..d6e26f1 --- /dev/null +++ b/Resources/404.html @@ -0,0 +1,14 @@ + + + + + + Hello! + + + +

Oops!

+

Sorry, I don't know what you're asking for.

+ + + diff --git a/Resources/Hello.html b/Resources/Hello.html new file mode 100644 index 0000000..d15414b --- /dev/null +++ b/Resources/Hello.html @@ -0,0 +1,14 @@ + + + + + + Hello! + + + +

Hello!

+

Hi from Rust

+ + + diff --git a/Source/Http.rs b/Source/Http.rs index d4b786d..8212210 100644 --- a/Source/Http.rs +++ b/Source/Http.rs @@ -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(); +} diff --git a/Source/Main.rs b/Source/Main.rs index a38b54f..76a040d 100644 --- a/Source/Main.rs +++ b/Source/Main.rs @@ -2,4 +2,6 @@ #![allow(non_snake_case)] -fn main() {} +fn main() { + Http::Main(); +}