Currently working on a web-server project on an ESP32-EVB (fantastic dev board, can't recommend it enough) using SPIFF partitions to store static resources for the site, including style-sheets, scripting, etc. I'm using the base WebServer.h library for Arduino ESP32 core, which has been working fine so far, but it's simplicity is starting to get annoying. On every request made by the client, the server has to be initialized to tie specific requests to specific handler functions. These ties need to be made in setup().
webServer.on("/", handleRoot);
webServer.on("/style.css", handleCSS);
webServer.on("/credits.html", handleCredits);
Here's a very similar bare-bones example for reference. This specificity is actually really useful if you want to implement a captive portal, which requires unique request handling when connecting to the endpoint from any type of device (iOS, Windows, Android, etc.), but not when you want to establish a fully-fledged static website, which requires dozens and dozens of files.
In short, there has to be a better way to handle file requests other than setting the server to call a handler for each and every static file that could be requested from the browser. Ideally, I imagine I could parse the GET request, get the filename its asking for and just pass that as a string to a single handler that will serve that from the SPIFF partition, but I can't find any documentation or examples that do that. Where can I go from here?
void handleRoot() {
char content[400];
snprintf(content, 400, readFile(SPIFFS, "/index.html"));
webServer.send(200, "text/html", content);
}
void handleWindows() {
webServer.send(200, "text/plain", "Microsoft NCSI");
webServer.send(200, "text/plain", "Hello from your badge!");
}
void handleAndroid() {
webServer.send(204, "text/plain", "");
}
void setup() {
WiFi.mode(WIFI_AP);
WiFi.softAPConfig(apIP, apIP, IPAddress(255, 255, 255, 0));
WiFi.softAP("Captive Portal Endpoint");
dnsServer.start(DNS_PORT, "*", apIP);
if (!startSPIFFS)
Serial.println("SPIFFS beef'd it.");
webServer.on("/", handleRoot);
/* ######################### Detection Portal Init ######################### */
// Apple
webServer.on("/hotspot-detect.html", handleRoot);
webServer.on("/success.html", handleRoot);
// Android/ChromeOS
webServer.on("/generate_204", handleRoot);
//Microsoft
webServer.on("/fwlink", handleRoot);
webServer.on("/ncsi.txt", handleWindows);
webServer.onNotFound([]() {
webServer.send(200, "text/html", responseHTML);
});
webServer.begin();
}
void loop() {
dnsServer.processNextRequest();
webServer.handleClient();
}
Found the solution after a lot more digging. Turns out, one of the settings on the WebServer is
.serveStatic()that does exactly what it sounds like. With this set true, the site is able to directly request any other static files it needs. Keeping this up in case anyone else needs to see this (also why the -1, dude?).