From fd0d75ee167d44c83b79d103f71b212846975958 Mon Sep 17 00:00:00 2001 From: Thomas Kolb Date: Wed, 20 Nov 2019 22:42:35 +0100 Subject: [PATCH] HTTPServer: serve static file from the SPIFFS --- include/HTTPServer.h | 2 ++ src/HTTPServer.cpp | 28 ++++++++++++++++++++++------ 2 files changed, 24 insertions(+), 6 deletions(-) diff --git a/include/HTTPServer.h b/include/HTTPServer.h index 1f8162f..8256050 100644 --- a/include/HTTPServer.h +++ b/include/HTTPServer.h @@ -28,6 +28,8 @@ class HTTPServer static void serverTask(void *arg); + static void serveFile(String filename, httpsserver::HTTPResponse *res); + // handlers static void handleRoot(httpsserver::HTTPRequest *req, httpsserver::HTTPResponse *res); static void handleColor(httpsserver::HTTPRequest *req, httpsserver::HTTPResponse *res); diff --git a/src/HTTPServer.cpp b/src/HTTPServer.cpp index dbedffe..8fc5354 100644 --- a/src/HTTPServer.cpp +++ b/src/HTTPServer.cpp @@ -1,5 +1,7 @@ /* HTTP Server setup and handler functions */ +#include + #include "HTTPServer.h" #include "Fader.h" @@ -10,14 +12,28 @@ HTTPServer::HTTPServer(void) m_server = new httpsserver::HTTPServer(); } +void HTTPServer::serveFile(String filename, httpsserver::HTTPResponse *res) +{ + uint8_t buf[1024]; + File f = SPIFFS.open(filename.c_str(), "r"); + + size_t nread = 1; + while(nread > 0) { + nread = f.readBytes(reinterpret_cast(buf), 1024); + if(nread <= 0) { + break; + } + + res->write(buf, nread); + } + + f.close(); +} + void HTTPServer::handleRoot(httpsserver::HTTPRequest *req, httpsserver::HTTPResponse *res) { - res->setHeader("Content-Type", "text/plain"); - - res->println("Hello World!"); - res->print("Uptime: "); - res->print(millis()); - res->println(" ms"); + serveFile("/index.html", res); + res->setHeader("Content-Type", "text/html"); } static void error400(httpsserver::HTTPResponse *res, const std::string &reason)