Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Custom ESP8266WebServer RequestHandler sample
#ifndef ABOUT_PAGE_H
#define ABOUT_PAGE_H
#include <ESP8266WebServer.h>
class AboutPage : public RequestHandler {
public:
AboutPage(const char* uri = "about")
: _uri(uri)
{
}
bool handle(ESP8266WebServer& server, HTTPMethod requestMethod, String requestUri) override {
if (requestMethod != HTTP_GET || requestUri != _uri) {
return false;
}
server.send(200, "text/plain", "This is an about page");
return true;
}
protected:
String _uri;
};
#endif //ABOUT_PAGE_H
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#include "AboutPage.h"
const char* ssid = "..........";
const char* password = "..........";
ESP8266WebServer server(80);
const int led = 13;
void handleRoot() {
digitalWrite(led, 1);
server.send(200, "text/plain", "hello from esp8266!");
digitalWrite(led, 0);
}
void setup(void){
pinMode(led, OUTPUT);
digitalWrite(led, 0);
Serial.begin(115200);
WiFi.begin(ssid, password);
Serial.println("");
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
if (MDNS.begin("esp8266")) {
Serial.println("MDNS responder started");
}
server.on("/", handleRoot);
server.addHandler(new AboutPage("/about"));
server.begin();
Serial.println("HTTP server started");
}
void loop(void){
server.handleClient();
}
@NicRoche

This comment has been minimized.

Copy link

NicRoche commented Sep 21, 2016

Hi Ivan,

This approach would solve some issues I am trying to overcome.

Problem is, I can't get the about handler to kick in when /about is requested - "not found" only.

Are there extra steps implied?

Is there a specific version of core this worked with?

I expect that requesting http://192.168.0.132/about should do it.

http://192.168.0.132/ works as expected.

Thanks,
Nic

@dex7fp

This comment has been minimized.

Copy link

dex7fp commented Dec 18, 2016

Hi Nic,

you have to implement the canHandle method, because default implementation is return false and you won't get control.

...
bool canHandle(HTTPMethod method, String uri) override {
if (method != HTTP_GET || uri != _uri) {
return false;
}
return true;
}

bool handle(ESP8266WebServer& server, HTTPMethod requestMethod, String requestUri) override {	
	if (!canHandle(requestMethod, requestUri)) { 
		return false;
	}

	server.send(200, "text/plain", "This is an about page");

	return true;
}

...

For me this was solution.

Regards,
Dex

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.