Implemented http status codes and htmlbuilder

This commit is contained in:
2021-09-18 18:01:50 +02:00
parent 4ebd651a70
commit 148e02b6ca
6 changed files with 262 additions and 34 deletions

View File

@ -1,9 +1,12 @@
set(headers
src/esphttpdutils.h
src/esphttpstatuscodes.h
src/htmlbuilder.h
)
set(sources
src/esphttpdutils.cpp
src/esphttpstatuscodes.cpp
)
set(dependencies

View File

@ -7,14 +7,14 @@
// 3rdparty lib includes
#include <fmt/core.h>
// local includes
// 3rdparty lib includes
#include "futurecpp.h"
#include "espcppmacros.h"
namespace esphttpdutils {
namespace {
constexpr const char * const TAG = "ESPHTTPDUTILS";
}
} // namespace
void urldecode(char *dst, const char *src)
{
@ -61,28 +61,6 @@ tl::expected<void, std::string> urlverify(std::string_view str)
return {};
}
const char *errorToStatus(httpd_err_code_t error)
{
switch (error)
{
case HTTPD_501_METHOD_NOT_IMPLEMENTED: return "501 Method Not Implemented";
case HTTPD_505_VERSION_NOT_SUPPORTED: return "505 Version Not Supported";
case HTTPD_400_BAD_REQUEST: return "400 Bad Request";
case HTTPD_401_UNAUTHORIZED: return "401 Unauthorized";
case HTTPD_403_FORBIDDEN: return "403 Forbidden";
case HTTPD_404_NOT_FOUND: return "404 Not Found";
case HTTPD_405_METHOD_NOT_ALLOWED: return "405 Method Not Allowed";
case HTTPD_408_REQ_TIMEOUT: return "408 Request Timeout";
case HTTPD_414_URI_TOO_LONG: return "414 URI Too Long";
case HTTPD_411_LENGTH_REQUIRED: return "411 Length Required";
case HTTPD_431_REQ_HDR_FIELDS_TOO_LARGE: return "431 Request Header Fields Too Large";
default:
ESP_LOGW(TAG, "unknown httpd_err_code_t(%i)", std::to_underlying(error));
[[fallthrough]];
case HTTPD_500_INTERNAL_SERVER_ERROR: return "500 Internal Server Error";
}
}
esp_err_t webserver_prepare_response(httpd_req_t *req)
{
CALL_AND_EXIT_ON_ERROR(httpd_resp_set_hdr, req, "Connection", "close")
@ -91,21 +69,27 @@ esp_err_t webserver_prepare_response(httpd_req_t *req)
return ESP_OK;
}
esp_err_t webserver_resp_send_succ(httpd_req_t *req, const char *type, std::string_view body)
esp_err_t webserver_resp_send(httpd_req_t *req, ResponseStatus error, const char *type, std::string_view body)
{
CALL_AND_EXIT_ON_ERROR(httpd_resp_set_status, req, toString(error))
CALL_AND_EXIT_ON_ERROR(httpd_resp_set_type, req, type)
CALL_AND_EXIT_ON_ERROR(httpd_resp_send, req, body.data(), body.size())
return ESP_OK;
}
esp_err_t webserver_resp_send_err(httpd_req_t *req, httpd_err_code_t error, const char *type, std::string_view body)
tl::expected<std::string, std::string> webserver_get_query(httpd_req_t *req)
{
CALL_AND_EXIT_ON_ERROR(httpd_resp_set_status, req, errorToStatus(error))
CALL_AND_EXIT_ON_ERROR(httpd_resp_set_type, req, type)
CALL_AND_EXIT_ON_ERROR(httpd_resp_send, req, body.data(), body.size())
std::string query;
return ESP_OK;
if (const size_t queryLength = httpd_req_get_url_query_len(req))
{
query.resize(queryLength);
if (const auto result = httpd_req_get_url_query_str(req, query.data(), query.size() + 1); result != ESP_OK)
return tl::make_unexpected(fmt::format("httpd_req_get_url_query_str() failed with {}", esp_err_to_name(result)));
}
return query;
}
} // namespace esphttpdutils

View File

@ -10,6 +10,9 @@
// 3rdparty lib includes
#include <tl/expected.hpp>
// local includes
#include "esphttpstatuscodes.h"
namespace esphttpdutils {
template<typename T> T htmlentities(const T &val) { return val; } // TODO
@ -19,11 +22,10 @@ void urldecode(char *dst, const char *src);
tl::expected<void, std::string> urlverify(std::string_view str);
const char *errorToStatus(httpd_err_code_t error);
esp_err_t webserver_prepare_response(httpd_req_t *req);
esp_err_t webserver_resp_send_succ(httpd_req_t *req, const char *type, std::string_view body);
esp_err_t webserver_resp_send_err(httpd_req_t *req, httpd_err_code_t error, const char *type, std::string_view body);
esp_err_t webserver_resp_send(httpd_req_t *req, ResponseStatus error, const char *type, std::string_view body);
tl::expected<std::string, std::string> webserver_get_query(httpd_req_t *req);
} // namespace esphttpdutils

View File

@ -0,0 +1,87 @@
#include "esphttpstatuscodes.h"
// esp-idf includes
#include <esp_log.h>
// 3rdparty lib includes
#include "futurecpp.h"
namespace esphttpdutils {
namespace {
constexpr const char * const TAG = "ESPHTTPDUTILS";
} // namespace
const char *toString(ResponseStatus status)
{
switch (status)
{
case ResponseStatus::Continue: return "100 Continue";
case ResponseStatus::SwitchingProtocols: return "101 Switching Protocols";
case ResponseStatus::Processing: return "102 Processing";
case ResponseStatus::EarlyHints: return "103 Early Hints";
case ResponseStatus::Ok: return "200 OK";
case ResponseStatus::Created: return "201 Created";
case ResponseStatus::Accepted: return "202 Accepted";
case ResponseStatus::NonAuthoritativeInformation: return "203 Non-Authoritative Information";
case ResponseStatus::NoContent: return "204 No Content";
case ResponseStatus::ResetContent: return "205 Reset Content";
case ResponseStatus::PartialContent: return "206 Partial Content";
case ResponseStatus::MultiStatus: return "207 Multi-Status";
case ResponseStatus::AlreadyReported: return "208 Already Reported";
case ResponseStatus::IMUsed: return "226 IM Used";
case ResponseStatus::MultipleChoices: return "300 Multiple Choices";
case ResponseStatus::MovedPermanently: return "301 Moved Permanently";
case ResponseStatus::Found: return "302 Found";
case ResponseStatus::SeeOther: return "303 See Other";
case ResponseStatus::NotModified: return "304 Not Modified";
case ResponseStatus::UseProxy: return "305 Use Proxy";
case ResponseStatus::SwitchProxy: return "306 Switch Proxy";
case ResponseStatus::TemporaryRedirect: return "307 Temporary Redirect";
case ResponseStatus::PermanentRedirect: return "308 Permanent Redirect";
case ResponseStatus::BadRequest: return "400 Bad Request";
case ResponseStatus::Unauthorized: return "401 Unauthorized";
case ResponseStatus::PaymentRequired: return "402 Payment Required";
case ResponseStatus::Forbidden: return "403 Forbidden";
case ResponseStatus::NotFound: return "404 Not Found";
case ResponseStatus::MethodNotAllowed: return "405 Method Not Allowed";
case ResponseStatus::NotAcceptable: return "406 Not Acceptable";
case ResponseStatus::ProxyAuthenticationRequired: return "407 Proxy Authentication Required";
case ResponseStatus::RequestTimeout: return "408 Request Timeout";
case ResponseStatus::Conflict: return "409 Conflict";
case ResponseStatus::Gone: return "410 Gone";
case ResponseStatus::LengthRequired: return "411 Length Required";
case ResponseStatus::PreconditionFailed: return "412 Precondition Failed";
case ResponseStatus::PayloadTooLarge: return "413 Payload Too Large";
case ResponseStatus::URITooLong: return "414 URI Too Long";
case ResponseStatus::UnsupportedMediaType: return "415 Unsupported Media Type";
case ResponseStatus::RangeNotSatisfiable: return "416 Range Not Satisfiable";
case ResponseStatus::ExpectationFailed: return "417 Expectation Failed";
case ResponseStatus::ImATeapot: return "418 I'm a teapot";
case ResponseStatus::MisdirectedRequest: return "421 Misdirected Request";
case ResponseStatus::UnprocessableEntity: return "422 Unprocessable Entity";
case ResponseStatus::Locked: return "423 Locked";
case ResponseStatus::FailedDependency: return "424 Failed Dependency";
case ResponseStatus::TooEarly: return "425 Too Early";
case ResponseStatus::UpgradeRequired: return "426 Upgrade Required";
case ResponseStatus::PreconditionRequired: return "428 Precondition Required";
case ResponseStatus::TooManyRequests: return "429 Too Many Requests";
case ResponseStatus::RequestHeaderFieldsTooLarge: return "431 Request Header Fields Too Large";
case ResponseStatus::UnavailableForLegalReasons: return "451 Unavailable For Legal Reasons";
default:
ESP_LOGW(TAG, "unknown httpd_err_code_t(%i)", std::to_underlying(status));
[[fallthrough]];
case ResponseStatus::InternalServerError: return "500 Internal Server Error";
case ResponseStatus::NotImplemented: return "501 Not Implemented";
case ResponseStatus::BadGateway: return "502 Bad Gateway";
case ResponseStatus::ServiceUnavailable: return "503 Service Unavailable";
case ResponseStatus::GatewayTimeout: return "504 Gateway Timeout";
case ResponseStatus::HTTPVersionNotSupported: return "505 HTTP Version Not Supported";
case ResponseStatus::VariantAlsoNegotiates: return "506 Variant Also Negotiates";
case ResponseStatus::InsufficientStorage: return "507 Insufficient Storage";
case ResponseStatus::LoopDetected: return "508 Loop Detected";
case ResponseStatus::NotExtended: return "510 Not Extended";
case ResponseStatus::NetworkAuthenticationRequired: return "511 Network Authentication Required";
}
}
} // namespace esphttpdutils

99
src/esphttpstatuscodes.h Normal file
View File

@ -0,0 +1,99 @@
#pragma once
namespace esphttpdutils {
enum class ResponseStatus
{
/*####### 1xx - Informational #######*/
/* Indicates an interim response for communicating connection status
* or request progress prior to completing the requested action and
* sending a final response.
*/
Continue = 100, //!< Indicates that the initial part of a request has been received and has not yet been rejected by the server.
SwitchingProtocols = 101, //!< Indicates that the server understands and is willing to comply with the client's request, via the Upgrade header field, for a change in the application protocol being used on this connection.
Processing = 102, //!< Is an interim response used to inform the client that the server has accepted the complete request, but has not yet completed it.
EarlyHints = 103, //!< Indicates to the client that the server is likely to send a final response with the header fields included in the informational response.
/*####### 2xx - Successful #######*/
/* Indicates that the client's request was successfully received,
* understood, and accepted.
*/
Ok = 200, //!< Indicates that the request has succeeded.
Created = 201, //!< Indicates that the request has been fulfilled and has resulted in one or more new resources being created.
Accepted = 202, //!< Indicates that the request has been accepted for processing, but the processing has not been completed.
NonAuthoritativeInformation = 203, //!< Indicates that the request was successful but the enclosed payload has been modified from that of the origin server's 200 (OK) response by a transforming proxy.
NoContent = 204, //!< Indicates that the server has successfully fulfilled the request and that there is no additional content to send in the response payload body.
ResetContent = 205, //!< Indicates that the server has fulfilled the request and desires that the user agent reset the \"document view\", which caused the request to be sent, to its original state as received from the origin server.
PartialContent = 206, //!< Indicates that the server is successfully fulfilling a range request for the target resource by transferring one or more parts of the selected representation that correspond to the satisfiable ranges found in the requests's Range header field.
MultiStatus = 207, //!< Provides status for multiple independent operations.
AlreadyReported = 208, //!< Used inside a DAV:propstat response element to avoid enumerating the internal members of multiple bindings to the same collection repeatedly. [RFC 5842]
IMUsed = 226, //!< The server has fulfilled a GET request for the resource, and the response is a representation of the result of one or more instance-manipulations applied to the current instance.
/*####### 3xx - Redirection #######*/
/* Indicates that further action needs to be taken by the user agent
* in order to fulfill the request.
*/
MultipleChoices = 300, //!< Indicates that the target resource has more than one representation, each with its own more specific identifier, and information about the alternatives is being provided so that the user (or user agent) can select a preferred representation by redirecting its request to one or more of those identifiers.
MovedPermanently = 301, //!< Indicates that the target resource has been assigned a new permanent URI and any future references to this resource ought to use one of the enclosed URIs.
Found = 302, //!< Indicates that the target resource resides temporarily under a different URI.
SeeOther = 303, //!< Indicates that the server is redirecting the user agent to a different resource, as indicated by a URI in the Location header field, that is intended to provide an indirect response to the original request.
NotModified = 304, //!< Indicates that a conditional GET request has been received and would have resulted in a 200 (OK) response if it were not for the fact that the condition has evaluated to false.
UseProxy = 305, //!< \deprecated \parblock Due to security concerns regarding in-band configuration of a proxy. \endparblock
//!< The requested resource MUST be accessed through the proxy given by the Location field.
SwitchProxy = 306, //!< \deprecated No longer used. Originally meant "Subsequent requests should use the specified proxy."
TemporaryRedirect = 307, //!< Indicates that the target resource resides temporarily under a different URI and the user agent MUST NOT change the request method if it performs an automatic redirection to that URI.
PermanentRedirect = 308, //!< The target resource has been assigned a new permanent URI and any future references to this resource outght to use one of the enclosed URIs. [...] This status code is similar to 301 Moved Permanently (Section 7.3.2 of rfc7231), except that it does not allow rewriting the request method from POST to GET.
/*####### 4xx - Client Error #######*/
/* Indicates that the client seems to have erred.
*/
BadRequest = 400, //!< Indicates that the server cannot or will not process the request because the received syntax is invalid, nonsensical, or exceeds some limitation on what the server is willing to process.
Unauthorized = 401, //!< Indicates that the request has not been applied because it lacks valid authentication credentials for the target resource.
PaymentRequired = 402, //!< *Reserved*
Forbidden = 403, //!< Indicates that the server understood the request but refuses to authorize it.
NotFound = 404, //!< Indicates that the origin server did not find a current representation for the target resource or is not willing to disclose that one exists.
MethodNotAllowed = 405, //!< Indicates that the method specified in the request-line is known by the origin server but not supported by the target resource.
NotAcceptable = 406, //!< Indicates that the target resource does not have a current representation that would be acceptable to the user agent, according to the proactive negotiation header fields received in the request, and the server is unwilling to supply a default representation.
ProxyAuthenticationRequired = 407, //!< Is similar to 401 (Unauthorized), but indicates that the client needs to authenticate itself in order to use a proxy.
RequestTimeout = 408, //!< Indicates that the server did not receive a complete request message within the time that it was prepared to wait.
Conflict = 409, //!< Indicates that the request could not be completed due to a conflict with the current state of the resource.
Gone = 410, //!< Indicates that access to the target resource is no longer available at the origin server and that this condition is likely to be permanent.
LengthRequired = 411, //!< Indicates that the server refuses to accept the request without a defined Content-Length.
PreconditionFailed = 412, //!< Indicates that one or more preconditions given in the request header fields evaluated to false when tested on the server.
PayloadTooLarge = 413, //!< Indicates that the server is refusing to process a request because the request payload is larger than the server is willing or able to process.
URITooLong = 414, //!< Indicates that the server is refusing to service the request because the request-target is longer than the server is willing to interpret.
UnsupportedMediaType = 415, //!< Indicates that the origin server is refusing to service the request because the payload is in a format not supported by the target resource for this method.
RangeNotSatisfiable = 416, //!< Indicates that none of the ranges in the request's Range header field overlap the current extent of the selected resource or that the set of ranges requested has been rejected due to invalid ranges or an excessive request of small or overlapping ranges.
ExpectationFailed = 417, //!< Indicates that the expectation given in the request's Expect header field could not be met by at least one of the inbound servers.
ImATeapot = 418, //!< Any attempt to brew coffee with a teapot should result in the error code 418 I'm a teapot.
MisdirectedRequest = 421, //!< The request was directed at a server that is not able to produce a response (for example because of connection reuse).
UnprocessableEntity = 422, //!< Means the server understands the content type of the request entity (hence a 415(Unsupported Media Type) status code is inappropriate), and the syntax of the request entity is correct (thus a 400 (Bad Request) status code is inappropriate) but was unable to process the contained instructions.
Locked = 423, //!< Means the source or destination resource of a method is locked.
FailedDependency = 424, //!< Means that the method could not be performed on the resource because the requested action depended on another action and that action failed.
TooEarly = 425, //!< Indicates that the server is unwilling to risk processing a request that might be replayed.
UpgradeRequired = 426, //!< Indicates that the server refuses to perform the request using the current protocol but might be willing to do so after the client upgrades to a different protocol.
PreconditionRequired = 428, //!< Indicates that the origin server requires the request to be conditional.
TooManyRequests = 429, //!< Indicates that the user has sent too many requests in a given amount of time (\"rate limiting\").
RequestHeaderFieldsTooLarge = 431, //!< Indicates that the server is unwilling to process the request because its header fields are too large.
UnavailableForLegalReasons = 451, //!< This status code indicates that the server is denying access to the resource in response to a legal demand.
/*####### 5xx - Server Error #######*/
/* Indicates that the server is aware that it has erred
* or is incapable of performing the requested method.
*/
InternalServerError = 500, //!< Indicates that the server encountered an unexpected condition that prevented it from fulfilling the request.
NotImplemented = 501, //!< Indicates that the server does not support the functionality required to fulfill the request.
BadGateway = 502, //!< Indicates that the server, while acting as a gateway or proxy, received an invalid response from an inbound server it accessed while attempting to fulfill the request.
ServiceUnavailable = 503, //!< Indicates that the server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay.
GatewayTimeout = 504, //!< Indicates that the server, while acting as a gateway or proxy, did not receive a timely response from an upstream server it needed to access in order to complete the request.
HTTPVersionNotSupported = 505, //!< Indicates that the server does not support, or refuses to support, the protocol version that was used in the request message.
VariantAlsoNegotiates = 506, //!< Indicates that the server has an internal configuration error: the chosen variant resource is configured to engage in transparent content negotiation itself, and is therefore not a proper end point in the negotiation process.
InsufficientStorage = 507, //!< Means the method could not be performed on the resource because the server is unable to store the representation needed to successfully complete the request.
LoopDetected = 508, //!< Indicates that the server terminated an operation because it encountered an infinite loop while processing a request with "Depth: infinity". [RFC 5842]
NotExtended = 510, //!< The policy for accessing the resource has not been met in the request. [RFC 2774]
NetworkAuthenticationRequired = 511, //!< Indicates that the client needs to authenticate to gain network access.
};
const char *toString(ResponseStatus status);
} // namespace esphttpdutils

53
src/htmlbuilder.h Normal file
View File

@ -0,0 +1,53 @@
#pragma once
// system includes
#include <string>
#include <string_view>
namespace esphttpdutils {
class HtmlTag
{
public:
HtmlTag(std::string_view tagName, std::string &body);
HtmlTag(std::string_view tagName, std::string_view attributes, std::string &body);
~HtmlTag();
private:
const std::string_view m_tagName;
std::string &m_body;
};
inline HtmlTag::HtmlTag(std::string_view tagName, std::string &body) :
m_tagName{tagName},
m_body{body}
{
m_body += '<';
m_body += m_tagName;
m_body += '>';
}
inline HtmlTag::HtmlTag(std::string_view tagName, std::string_view attributes, std::string &body) :
m_tagName{tagName},
m_body{body}
{
m_body += '<';
m_body += m_tagName;
if (!attributes.empty())
{
m_body += ' ';
m_body += attributes;
}
m_body += '>';
}
inline HtmlTag::~HtmlTag()
{
m_body += "</";
m_body += m_tagName;
m_body += '>';
}
} // namespace esphttpdutils