Skip to content

Instantly share code, notes, and snippets.

@igrr
Created October 6, 2015 12:29
Show Gist options
  • Save igrr/0da0c4adc7588d9bd911 to your computer and use it in GitHub Desktop.
Save igrr/0da0c4adc7588d9bd911 to your computer and use it in GitHub Desktop.
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();
}
@dex7fp
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

@p43k
Copy link

p43k commented Oct 16, 2022

for me was solution change from
bool handle(ESP8266WebServer& server, HTTPMethod requestMethod, String requestUri);
to
bool handle(ESP8266WebServer& server, HTTPMethod requestMethod, const String& requestUri);
and of corse
bool canHandle(HTTPMethod requestMethod, String requestUri);
to
bool canHandle(HTTPMethod requestMethod, const String& requestUri);
In respect
p43k

@yuanminglove
Copy link

p43k goooood

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment