HTTPServer.h 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. #include <unistd.h>
  14. #include <sstream>
  15. #include <BellLogger.h>
  16. #include <sys/select.h>
  17. #include <sys/types.h>
  18. #include <unistd.h>
  19. #include <fstream>
  20. #include <sys/socket.h>
  21. #include <string>
  22. #include <netdb.h>
  23. #include <mutex>
  24. #include <fcntl.h>
  25. #include "BaseHTTPServer.h"
  26. #ifndef SOCK_NONBLOCK
  27. #define SOCK_NONBLOCK O_NONBLOCK
  28. #endif
  29. namespace bell
  30. {
  31. class HTTPServer : public bell::BaseHTTPServer
  32. {
  33. private:
  34. std::regex routerPattern = std::regex(":([^\\/]+)?");
  35. fd_set master;
  36. fd_set readFds;
  37. fd_set activeFdSet, readFdSet;
  38. bool isClosed = true;
  39. bool writingResponse = false;
  40. std::map<std::string, std::vector<HTTPRoute>> routes;
  41. std::map<int, HTTPConnection> connections;
  42. void writeResponse(const HTTPResponse &);
  43. void writeResponseEvents(int connFd);
  44. void findAndHandleRoute(std::string &, std::string &, int connectionFd);
  45. std::vector<std::string> splitUrl(const std::string &url, char delimiter);
  46. std::mutex responseMutex;
  47. std::vector<char> responseBuffer = std::vector<char>(128);
  48. void readFromClient(int clientFd);
  49. std::map<std::string, std::string> parseQueryString(const std::string &queryString);
  50. unsigned char h2int(char c);
  51. std::string urlDecode(std::string str);
  52. public:
  53. HTTPServer(int serverPort);
  54. void registerHandler(RequestType requestType, const std::string &, httpHandler);
  55. void respond(const HTTPResponse &);
  56. void publishEvent(std::string eventName, std::string eventData);
  57. void closeConnection(int connection);
  58. void listen();
  59. };
  60. }
  61. #endif