server.h 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. #ifndef KBF_HTTP_SERVER_H
  2. #define KBF_HTTP_SERVER_H
  3. #include <string>
  4. #include <vector>
  5. #include <map>
  6. #include <esp_http_server.h>
  7. #include "kbf/http/common.h"
  8. using std::string;
  9. using std::vector;
  10. using std::map;
  11. namespace kbf::http {
  12. /** @brief HTTP Server */
  13. class Server {
  14. public:
  15. /** @brief Tag used for logging. */
  16. static constexpr const char *TAG = "kbf::http::Server";
  17. /**
  18. * @brief Destructor.
  19. *
  20. * Will call stop() if #running.
  21. */
  22. ~Server();
  23. /**
  24. * @brief Holds information about a route and it's handler.
  25. */
  26. struct Route {
  27. public:
  28. /** @brief HTTP method */
  29. http::Method method;
  30. /**
  31. * @brief URI
  32. *
  33. * @example "/"
  34. * @example "/foo"
  35. */
  36. const string uri;
  37. /**
  38. * @brief Request handler function.
  39. *
  40. * @param request Request sent by a client
  41. * @param data custom data passed to the request handler function
  42. * @return Response to be sent to the client
  43. */
  44. Response (*handler)(const Request &request, void *data);
  45. /**
  46. * @brief Custom data passed to the request handler function.
  47. */
  48. void *data; // TODO doesn't belong in Route... maybe pass it to route()?
  49. };
  50. /**
  51. * @brief Adds a Route handler.
  52. *
  53. * @note All routes must be added before calling start().
  54. *
  55. * @note Removing routes is not yet supported.
  56. *
  57. * @param route Route to add
  58. * @return *this (to enable builder-like syntax)
  59. */
  60. Server &route(Route route);
  61. /**
  62. * @brief Starts the HTTP server.
  63. *
  64. * @param port TCP port, default is 80
  65. * @return *this (to enable builder-like syntax)
  66. */
  67. Server &start(int port = 80);
  68. /**
  69. * @brief Starts the server in SSL (HTTPS) mode.
  70. *
  71. * @param port TCP port, default is 443
  72. * @return *this (to enable builder-like syntax)
  73. */
  74. Server &startSSL(int port = 443);
  75. /**
  76. * @brief Stops the HTTP server.
  77. */
  78. void stop();
  79. /**
  80. * @brief Returns whether the server is running.
  81. *
  82. * @return true if server is running; false otherwise
  83. */
  84. [[nodiscard]] bool isRunning() const { return running; }
  85. private:
  86. bool running = false;
  87. httpd_handle_t handle = nullptr;
  88. vector<Route> routes;
  89. static esp_err_t handleHttpRequest(httpd_req_t *httpdRequest);
  90. void registerUriHandlers();
  91. };
  92. }
  93. #endif //KBF_HTTP_SERVER_H