2
0

HTTPServer.h 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. #ifndef BELL_HTTP_SERVER_H
  2. #define BELL_HTTP_SERVER_H
  3. #include <functional>
  4. #include <map>
  5. #include <optional>
  6. #include <memory>
  7. #include <regex>
  8. #include <optional>
  9. #include <set>
  10. #include <iostream>
  11. #include <queue>
  12. #include <stdio.h>
  13. #ifdef _WIN32
  14. #include <winsock2.h>
  15. #include <ws2tcpip.h>
  16. #include "win32shim.h"
  17. #else
  18. #include <sys/select.h>
  19. #include <sys/socket.h>
  20. #include <netdb.h>
  21. #include <unistd.h>
  22. #endif
  23. #include <sstream>
  24. #include <BellLogger.h>
  25. #include <sys/types.h>
  26. #include <fstream>
  27. #include <string>
  28. #include <mutex>
  29. #include <fcntl.h>
  30. #include "BaseHTTPServer.h"
  31. #ifndef SOCK_NONBLOCK
  32. #define SOCK_NONBLOCK O_NONBLOCK
  33. #endif
  34. namespace bell
  35. {
  36. class HTTPServer : public bell::BaseHTTPServer
  37. {
  38. private:
  39. std::regex routerPattern = std::regex(":([^\\/]+)?");
  40. fd_set master;
  41. fd_set readFds;
  42. fd_set activeFdSet, readFdSet;
  43. bool isClosed = true;
  44. bool writingResponse = false;
  45. std::map<std::string, std::vector<HTTPRoute>> routes;
  46. std::map<int, HTTPConnection> connections;
  47. void writeResponse(const HTTPResponse &);
  48. void writeResponseEvents(int connFd);
  49. void findAndHandleRoute(HTTPConnection& connection);
  50. std::vector<std::string> splitUrl(const std::string &url, char delimiter);
  51. std::mutex responseMutex;
  52. std::vector<char> responseBuffer = std::vector<char>(128);
  53. void redirectCaptivePortal(int connectionFd);
  54. void readFromClient(int clientFd);
  55. std::map<std::string, std::string> parseQueryString(const std::string &queryString);
  56. unsigned char h2int(char c);
  57. std::string urlDecode(std::string str);
  58. public:
  59. HTTPServer(int serverPort);
  60. void registerHandler(RequestType requestType, const std::string &, httpHandler, bool readDataToStr = false);
  61. void respond(const HTTPResponse &);
  62. void redirectTo(const std::string&, int connectionFd);
  63. void publishEvent(std::string eventName, std::string eventData);
  64. void closeConnection(int connection);
  65. void listen();
  66. };
  67. }
  68. #endif