server.h 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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. * @return Response to be sent to the client
  42. */
  43. Response (*handler)(const Request &request);
  44. };
  45. /**
  46. * @brief Adds a Route handler.
  47. *
  48. * @note All routes must be added before calling start().
  49. *
  50. * @note Removing routes is not yet supported.
  51. *
  52. * @param route Route to add
  53. * @return *this (to enable builder-like syntax)
  54. */
  55. Server &route(Route route);
  56. /**
  57. * @brief Starts the HTTP server.
  58. *
  59. * @param port TCP port, default is 80
  60. * @return *this (to enable builder-like syntax)
  61. */
  62. Server &start(int port = 80);
  63. /**
  64. * @brief Stops the HTTP server.
  65. */
  66. void stop();
  67. /**
  68. * @brief Returns whether the server is running.
  69. *
  70. * @return true if server is running; false otherwise
  71. */
  72. [[nodiscard]] bool isRunning() const { return running; }
  73. private:
  74. bool running = false;
  75. httpd_handle_t handle = nullptr;
  76. vector<Route> routes;
  77. static esp_err_t handleHttpRequest(httpd_req_t *httpdRequest);
  78. };
  79. }
  80. #endif //KBF_HTTP_SERVER_H