WebServer: serve static files from SPIFFS
This commit is contained in:
parent
642ce82144
commit
13a758b01f
|
@ -15,11 +15,17 @@ WebServer::WebServer(void)
|
|||
m_server = new httpsserver::HTTPServer();
|
||||
}
|
||||
|
||||
void WebServer::serveFile(String filename, httpsserver::HTTPResponse *res)
|
||||
bool WebServer::serveFile(String filename, httpsserver::HTTPResponse *res)
|
||||
{
|
||||
uint8_t buf[1024];
|
||||
File f = SPIFFS.open(filename.c_str(), "r");
|
||||
|
||||
if(!f) {
|
||||
return false;
|
||||
}
|
||||
|
||||
res->setHeader("Content-Length", httpsserver::intToString(f.size()));
|
||||
|
||||
size_t nread = 1;
|
||||
while(nread > 0) {
|
||||
nread = f.readBytes(reinterpret_cast<char*>(buf), 1024);
|
||||
|
@ -31,6 +37,8 @@ void WebServer::serveFile(String filename, httpsserver::HTTPResponse *res)
|
|||
}
|
||||
|
||||
f.close();
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void WebServer::handleRoot(httpsserver::HTTPRequest *req, httpsserver::HTTPResponse *res)
|
||||
|
@ -174,8 +182,11 @@ void WebServer::handleAuthTest(httpsserver::HTTPRequest *req, httpsserver::HTTPR
|
|||
}
|
||||
}
|
||||
|
||||
void WebServer::handle404(httpsserver::HTTPRequest *req, httpsserver::HTTPResponse *res)
|
||||
void WebServer::handleStatic(httpsserver::HTTPRequest *req, httpsserver::HTTPResponse *res)
|
||||
{
|
||||
std::string filename = "/htdocs" + req->getRequestString();
|
||||
|
||||
if(!serveFile(filename.c_str(), res)) {
|
||||
req->discardRequestBody();
|
||||
|
||||
res->setStatusCode(404);
|
||||
|
@ -183,6 +194,7 @@ void WebServer::handle404(httpsserver::HTTPRequest *req, httpsserver::HTTPRespon
|
|||
|
||||
res->println("Error 404: Not found");
|
||||
}
|
||||
}
|
||||
|
||||
void WebServer::serverTask(void *arg)
|
||||
{
|
||||
|
@ -196,8 +208,10 @@ void WebServer::serverTask(void *arg)
|
|||
WebServer::handleChallenge);
|
||||
httpsserver::ResourceNode *nodeAuthTest = new httpsserver::ResourceNode("/authtest", "GET",
|
||||
WebServer::handleAuthTest);
|
||||
httpsserver::ResourceNode *node404 = new httpsserver::ResourceNode("", "GET",
|
||||
WebServer::handle404);
|
||||
|
||||
// handle all remaining requests by trying to serve static files. If no file is found, 404 is generated.
|
||||
httpsserver::ResourceNode *nodeStatic = new httpsserver::ResourceNode("", "GET",
|
||||
WebServer::handleStatic);
|
||||
|
||||
WebServer &server = WebServer::instance();
|
||||
|
||||
|
@ -206,7 +220,7 @@ void WebServer::serverTask(void *arg)
|
|||
server.m_server->registerNode(nodeUpdate);
|
||||
server.m_server->registerNode(nodeChallenge);
|
||||
server.m_server->registerNode(nodeAuthTest);
|
||||
server.m_server->setDefaultNode(node404);
|
||||
server.m_server->setDefaultNode(nodeStatic);
|
||||
|
||||
Serial.println("[server] Starting HTTP Server...");
|
||||
server.m_server->start();
|
||||
|
|
Loading…
Reference in a new issue