2
0

BaseHTTPServer.h 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  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::vector<std::string> extraHeaders = std::vector<std::string>();
  47. std::unique_ptr<ResponseReader> responseReader;
  48. };
  49. typedef std::function<void(HTTPRequest &)> httpHandler;
  50. struct HTTPRoute {
  51. RequestType requestType;
  52. httpHandler handler;
  53. };
  54. struct HTTPConnection {
  55. std::vector<uint8_t> buffer;
  56. std::string currentLine = "";
  57. int contentLength = 0;
  58. bool isReadingBody = false;
  59. std::string httpMethod;
  60. bool toBeClosed = false;
  61. bool isEventConnection = false;
  62. };
  63. class BaseHTTPServer {
  64. public:
  65. BaseHTTPServer() {};
  66. virtual ~BaseHTTPServer() = default;
  67. /**
  68. * Should contain server's bind port
  69. */
  70. int serverPort;
  71. /**
  72. * Called when handler is being registered on the http server
  73. *
  74. * @param requestType GET or POST
  75. * @param endpoint registering under
  76. * httpHandler lambda to be called when given endpoint gets executed
  77. */
  78. virtual void registerHandler(RequestType requestType, const std::string & endpoint,
  79. httpHandler) = 0;
  80. /**
  81. * Writes given response to a fd
  82. */
  83. virtual void respond(const HTTPResponse &) = 0;
  84. };
  85. } // namespace bell
  86. #endif