1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586 |
- #include "kbf/http/server.h"
- #include <esp_log.h>
- #include <memory>
- #include "kbf/macros.h"
- using namespace kbf;
- http::Server &http::Server::route(http::Server::Route route) {
- ESP_LOGD(TAG, "adding route: %s", route.uri.c_str());
- routes.push_back(route);
- return *this;
- }
- http::Server &http::Server::start(int port) {
- ESP_LOGI(TAG, "starting HTTP server on port %d", port);
- if (running) {
- ESP_LOGE(TAG, "server already running");
- ABORT("fix me");
- }
- handle = nullptr;
- httpd_config_t config = HTTPD_DEFAULT_CONFIG();
- config.server_port = port;
- config.stack_size = 16384;
- CHECK(httpd_start(&handle, &config));
- ESP_LOGI(TAG, "registering URI handlers");
- for (auto &route : routes) {
- ESP_LOGI(TAG, " method: %d; uri: %s", static_cast<int>(route.method), route.uri.c_str());
- httpd_uri_t uriHandler = {
- .uri = route.uri.c_str(),
- .method = static_cast<httpd_method_t>(route.method),
- .handler = handleHttpRequest,
- .user_ctx = &route
- };
- CHECK(httpd_register_uri_handler(handle, &uriHandler));
- }
- running = true;
- return *this;
- }
- void http::Server::stop() {
- CHECK(httpd_stop(handle));
- running = false;
- }
- // TODO handle all status codes; also maybe use macro or constexpr or something?
- static string getDefaultStatusText(int status) {
- if (status == 200) return "OK";
- if (status == 204) return "No Content";
- if (status == 400) return "Bad Request";
- if (status == 500) return "Internal Server Error";
- return "Unknown HTTP Status";
- }
- esp_err_t http::Server::handleHttpRequest(httpd_req_t *httpdRequest) {
- auto route = static_cast<Route *>(httpdRequest->user_ctx);
- ESP_LOGD(TAG, "incoming request: method %d, path %s", httpdRequest->method, route->uri.c_str());
- auto request = Request(httpdRequest);
- auto response = route->handler(request);
- CHECK(httpd_resp_set_hdr(httpdRequest, "Server", "kbf_http_server/0.1"));
- CHECK(httpd_resp_set_type(httpdRequest, response.contentType.c_str()));
- for (const auto &[name, value] : response.headers) {
- CHECK(httpd_resp_set_hdr(httpdRequest, name.c_str(), value.c_str()));
- }
- if (response.statusText.empty()) {
- response.statusText = getDefaultStatusText(response.status);
- }
- string status = std::to_string(response.status) + " " + response.statusText;
- ESP_LOGD(TAG, "sending response with status: %s", status.c_str());
- CHECK(httpd_resp_set_status(httpdRequest, status.c_str()));
- CHECK(httpd_resp_send(httpdRequest, response.body.c_str(), response.body.length()));
- return ESP_OK;
- }
- http::Server::~Server() {
- if (running) stop();
- }
|