From effa9ec9fa17c42aabe6c8157af4365a2f5d60ef Mon Sep 17 00:00:00 2001 From: cat Date: Thu, 26 Jun 2025 02:07:58 +0300 Subject: [PATCH] Added proper file reading --- src/HTTP.cpp | 20 ++++++++++---------- src/Helpers.cpp | 11 +++++++++++ src/Helpers.hpp | 2 ++ 3 files changed, 23 insertions(+), 10 deletions(-) diff --git a/src/HTTP.cpp b/src/HTTP.cpp index a156ecb..4b063a1 100644 --- a/src/HTTP.cpp +++ b/src/HTTP.cpp @@ -47,25 +47,25 @@ void HTTPrequest::processRequest( // // This is where we will process requests // - std::stringstream responseStream; - std::string responseMeta = "\nContent-Type: text/html\nConnection: close\n\n"; - responseStream << "HTTP/1.1 "; // This is very much temp if (requestType != "GET") { - responseStream << "403 Forbidden" << responseMeta << "No POST allowed"; - writeData(responseStream.str()); + writeData(Helpers::GenerateResponse("403 Forbidden", "text/text", + "POST requests are not allowed!")); return; } - // This needs to read from a file instead of by hand + // This can be further refactored to just "File send" switch (Helpers::Pathhash(requestPath)) { case "/"_hash: - responseStream << "200 OK" << responseMeta - << Helpers::ReadFile("www/index.html"); - break; + writeData(Helpers::GenerateResponse("200 OK", "text/html", + Helpers::ReadFile("www/index.html"))); + return; + default: + writeData(Helpers::GenerateResponse("404 Not Found", "text/html", + "Could not find that file!!")); + return; } - writeData(responseStream.str()); } void HTTPrequest::writeData(std::string data) { diff --git a/src/Helpers.cpp b/src/Helpers.cpp index aaf1138..1f6fda7 100644 --- a/src/Helpers.cpp +++ b/src/Helpers.cpp @@ -1,6 +1,7 @@ #include "Helpers.hpp" #include #include +#include // Should add caching here std::string Helpers::ReadFile(std::string Path) { @@ -9,3 +10,13 @@ std::string Helpers::ReadFile(std::string Path) { contents << file.rdbuf(); return contents.str(); } + +std::string Helpers::GenerateResponse(std::string statusCode, + std::string contentType, + std::string content) { + std::stringstream output; + output << "HTTP/1.1 " << statusCode << "\n" + << "Content-Type: " << contentType << "\nConnection: close\n\n" + << content; + return output.str(); +} diff --git a/src/Helpers.hpp b/src/Helpers.hpp index 43c2a43..bf5d91a 100644 --- a/src/Helpers.hpp +++ b/src/Helpers.hpp @@ -8,6 +8,8 @@ namespace Helpers { std::string ReadFile(std::string Path); +std::string GenerateResponse(std::string statusCode, std::string contentType, + std::string content); // =========== // Hashing // ===========