// Copyright 2021 Jeisson Hidalgo-Cespedes. Universidad de Costa Rica. CC BY 4.0 #include #include #include #include "TcpServer.hpp" #include "Socket.hpp" class HttpServer : public TcpServer { DISABLE_COPY(HttpServer); protected: HttpServer() = default; ~HttpServer() = default; void handleClientConnection(Socket& client) override { const char* const SERVER_NAME = "ToBeNamed"; std::ostringstream message; message << ""; message << "Hi!

Welcome!

"; message << "

Generated by " << SERVER_NAME << "

"; // Status line client << "HTTP/1.0 200 0K\r\n"; // Response header client << "Server: " << SERVER_NAME << "\r\n"; client << "Content-Type: text/html; charset=ascii\r\n"; client << "Content-Length: " << message.str().length() << "\r\n"; client << "\r\n"; // Body client << message.str(); client.send(); // char* leak = new char[message.str().length() + 1]; *leak = 0; } public: void stop() { std::cout << "Server stopped" << std::endl; this->stopListening(); } static HttpServer& getInstance() { static HttpServer server; return server; } }; void handleSignal(int signal) { HttpServer::getInstance().stop(); std::cout << "Signal: " << signal << std::endl; } int main(int argc, char* argv[]) { if ( argc >= 2 ) { ::signal(SIGINT, ::handleSignal); ::signal(SIGTERM, ::handleSignal); try { HttpServer::getInstance().listenForever(argv[1]); } catch (std::runtime_error& error) { } } }