123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596 |
- #ifndef KBF_HTTP_SERVER_H
- #define KBF_HTTP_SERVER_H
- #include <string>
- #include <vector>
- #include <map>
- #include <esp_http_server.h>
- #include "kbf/http/common.h"
- using std::string;
- using std::vector;
- using std::map;
- namespace kbf::http {
- /** @brief HTTP Server */
- class Server {
- public:
- /** @brief Tag used for logging. */
- static constexpr const char *TAG = "kbf::http::Server";
- /**
- * @brief Destructor.
- *
- * Will call stop() if #running.
- */
- ~Server();
- /**
- * @brief Holds information about a route and it's handler.
- */
- struct Route {
- public:
- /** @brief HTTP method */
- http::Method method;
- /**
- * @brief URI
- *
- * @example "/"
- * @example "/foo"
- */
- const string uri;
- /**
- * @brief Request handler function.
- *
- * @param request Request sent by a client
- * @return Response to be sent to the client
- */
- Response (*handler)(const Request &request);
- };
- /**
- * @brief Adds a Route handler.
- *
- * @note All routes must be added before calling start().
- *
- * @note Removing routes is not yet supported.
- *
- * @param route Route to add
- * @return *this (to enable builder-like syntax)
- */
- Server &route(Route route);
- /**
- * @brief Starts the HTTP server.
- *
- * @param port TCP port, default is 80
- * @return *this (to enable builder-like syntax)
- */
- Server &start(int port = 80);
- /**
- * @brief Stops the HTTP server.
- */
- void stop();
- /**
- * @brief Returns whether the server is running.
- *
- * @return true if server is running; false otherwise
- */
- [[nodiscard]] bool isRunning() const { return running; }
- private:
- bool running = false;
- httpd_handle_t handle = nullptr;
- vector<Route> routes;
- static esp_err_t handleHttpRequest(httpd_req_t *httpdRequest);
- };
- }
- #endif //KBF_HTTP_SERVER_H
|