2
0

BaseHTTPServer.h 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. #ifndef BELL_BASE_HTTP_SERV
  2. #define BELL_BASE_HTTP_SERV
  3. #include <cstdio>
  4. #include <string>
  5. #include <map>
  6. #include <memory>
  7. #include <functional>
  8. namespace bell {
  9. class ResponseReader {
  10. public:
  11. ResponseReader(){};
  12. virtual ~ResponseReader() = default;
  13. virtual size_t getTotalSize() = 0;
  14. virtual size_t read(char *buffer, size_t size) = 0;
  15. };
  16. class FileResponseReader : public ResponseReader {
  17. public:
  18. FILE *file;
  19. size_t fileSize;
  20. FileResponseReader(std::string fileName) {
  21. file = fopen(fileName.c_str(), "r");
  22. fseek(file, 0, SEEK_END); // seek to end of file
  23. fileSize = ftell(file); // get current file pointer
  24. fseek(file, 0, SEEK_SET); // seek back to beginning of file
  25. };
  26. ~FileResponseReader() { fclose(file); };
  27. size_t read(char *buffer, size_t size) {
  28. return fread(buffer, 1, size, file);
  29. }
  30. size_t getTotalSize() { return fileSize; }
  31. };
  32. enum class RequestType { GET, POST };
  33. struct HTTPRequest {
  34. std::map<std::string, std::string> urlParams;
  35. std::map<std::string, std::string> queryParams;
  36. std::string body;
  37. int handlerId;
  38. int connection;
  39. };
  40. struct HTTPResponse {
  41. int connectionFd;
  42. int status;
  43. bool useGzip = false;
  44. std::string body;
  45. std::string contentType;
  46. std::unique_ptr<ResponseReader> responseReader;
  47. };
  48. typedef std::function<void(HTTPRequest &)> httpHandler;
  49. struct HTTPRoute {
  50. RequestType requestType;
  51. httpHandler handler;
  52. };
  53. struct HTTPConnection {
  54. std::vector<uint8_t> buffer;
  55. std::string currentLine = "";
  56. int contentLength = 0;
  57. bool isReadingBody = false;
  58. std::string httpMethod;
  59. bool toBeClosed = false;
  60. bool isEventConnection = false;
  61. };
  62. class BaseHTTPServer {
  63. public:
  64. BaseHTTPServer() {};
  65. virtual ~BaseHTTPServer() = default;
  66. /**
  67. * Should contain server's bind port
  68. */
  69. int serverPort;
  70. /**
  71. * Called when handler is being registered on the http server
  72. *
  73. * @param requestType GET or POST
  74. * @param endpoint registering under
  75. * httpHandler lambda to be called when given endpoint gets executed
  76. */
  77. virtual void registerHandler(RequestType requestType, const std::string & endpoint,
  78. httpHandler) = 0;
  79. /**
  80. * Writes given response to a fd
  81. */
  82. virtual void respond(const HTTPResponse &) = 0;
  83. };
  84. } // namespace bell
  85. #endif