after the verification of the basic ESP8266WebServer functionality on my ESP8266 I wanted to refactor some setup methods into an own Class (which basically is an abstraction layer to the ESP8266WebServer class). Therefore I created an ESP8266WebServer pointer as a member of the class "Webserver" (see appended Code "Webserver.h" and "Webserver.cpp").
I now want to configure the server root route ("/") to serve the static HTML file "index.html" from SPIFFS. However when I use the "serveStatic" method as shown in "Webserver.cpp" my esp returns an empty response (ERR_EMPTY_RESPONSE) when accessing it via browser (this worked previously so it has to do with refactoring into a separate class).
After investigating this issue it turned out that others had similar issues (e.g. https://www.esp8266.com/viewtopic.php?f=32&t=4505 and https://stackoverflow.com/questions/43479328/how-to-pass-class-member-function-as-handler-function) when using the "server.on()" method in an encapsulated ESP8266WebServer instance. I verified that the fix would work, when I use "server.on()" (see comment in "Webserver.cpp"). However I was not able to apply the suggested fix (using std::bind) for my purpose.
I appreciate any suggestions and feedback.
Best regards,
GuyWithCookies
Webserver.h
/**
* Class that handles webserver initalization
**/
#ifndef WEBSERVER_H
#define WEBSERVER_H
#include <ESP8266HTTPClient.h>
#include <AutoConnect.h>
class Webserver {
public:
Webserver();
bool setup();
void handleClient();
void handleRoot();
private:
ESP8266WebServer* server;
void setupWebserverRoutes();
bool setupFileSystem();
};
#endif
Webserver.cpp
#include "Webserver.h"
#include <AutoConnect.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#include <iostream>
Webserver::Webserver() {
std::cout << "Create webserver instance" << std::endl;
this->server = new ESP8266WebServer();
}
void Webserver::handleRoot(){
char content[] = "Hello world";
this->server->send(200, "text/plain", content);
}
void Webserver::setupWebserverRoutes() {
// Using "server.on" works (hello world is displayed in browser).
// However I need to serve the index.html instead which uses serveStatic and produces the aforementioned
// issue
//this->server->on("/", std::bind(&Webserver::handleRoot, this));
this->server->serveStatic("/", SPIFFS, "/index.html");
};
bool Webserver::setupFileSystem() {
if (!SPIFFS.begin()) {
Serial.println("SPIFFS Mount failed");
return false;
} else {
Serial.println("SPIFFS Mount successfull");
return true;
}
};
bool Webserver::setup() {
// Setup all routes for the website
Webserver::setupWebserverRoutes();
if (!Webserver::setupFileSystem()) {
return false;
}
this->server->begin()
return true;
}
void Webserver::handleClient() {
this->server->handleClient();
}