From 13a758b01fc411895227e92075b54551388ba5c8 Mon Sep 17 00:00:00 2001 From: Thomas Kolb Date: Sun, 8 Dec 2019 22:56:59 +0100 Subject: [PATCH] WebServer: serve static files from SPIFFS --- src/WebServer.cpp | 34 ++++++++++++++++++++++++---------- 1 file changed, 24 insertions(+), 10 deletions(-) diff --git a/src/WebServer.cpp b/src/WebServer.cpp index 27596c7..897b0ef 100644 --- a/src/WebServer.cpp +++ b/src/WebServer.cpp @@ -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(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,14 +182,18 @@ 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) { - req->discardRequestBody(); + std::string filename = "/htdocs" + req->getRequestString(); - res->setStatusCode(404); - res->setHeader("Content-Type", "text/plain"); + if(!serveFile(filename.c_str(), res)) { + req->discardRequestBody(); - res->println("Error 404: Not found"); + res->setStatusCode(404); + res->setHeader("Content-Type", "text/plain"); + + 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(); @@ -234,4 +248,4 @@ bool WebServer::start(void) NULL); /* Task handle to keep track of created task */ return true; -} \ No newline at end of file +}