Async Http Server.
This class handles a fully asynchronous http server staying inside 5 fixed memory regions passed during init.
constexpr int MAX_CONNECTIONS = 3;
constexpr int REQUEST_SLICES = 2;
constexpr int REQUEST_SIZE = 1 * 1024;
constexpr int HEADER_SIZE = 8 * 1024;
using HttpConnectionType = HttpAsyncConnection<REQUEST_SLICES, REQUEST_SLICES, HEADER_SIZE, REQUEST_SIZE>;
HttpConnectionType connections[MAX_CONNECTIONS];
HttpAsyncServer httpServer;
SC_TEST_EXPECT(httpServer.init(Span<HttpConnectionType>(connections)));
struct ServerContext
{
int numRequests;
} serverContext = {0};
httpServer.onRequest = [this, &serverContext](HttpConnection& client)
{
HttpRequest& request = client.request;
HttpResponse& response = client.response;
if (request.getParser().method != HttpParser::Method::HttpGET)
{
return;
}
if (request.getURL() != "/index.html" and request.getURL() != "/")
{
return;
}
serverContext.numRequests++;
SC_TEST_EXPECT(response.addHeader(
"Date",
"Mon, 27 Aug 2023 16:37:00 GMT"));
SC_TEST_EXPECT(response.addHeader(
"Last-Modified",
"Wed, 27 Aug 2023 16:37:00 GMT"));
const char sampleHtml[] = "<html>\r\n"
"<body bgcolor=\"#000000\" text=\"#ffffff\">\r\n"
"<h1>This is a title {}!</h1>\r\n"
"We must start from somewhere\r\n"
"</body>\r\n"
"</html>\r\n";
String content;
SC_TEST_EXPECT(StringBuilder::format(content, sampleHtml, serverContext.numRequests));
SmallString<16> contentLength;
SC_TEST_EXPECT(StringBuilder::format(contentLength,
"{}", content.view().sizeInBytes()));
SC_TEST_EXPECT(response.addHeader(
"Content-Length", contentLength.view()));
};