Skip to content

Commit cd5c166

Browse files
ayushsharma82hasenradball
authored andcommitted
Implemented support for filters and removable routes in ESP8266WebServer (esp8266#9152)
* feat: added filters and removeable routes * Update Filters.ino * fix: clang-format * chore: updated docs * chore: updated doc * fix: use new implementation * fix: filters.ino example * fix: filters.ino * fix: formatting * fix: formatting (2)
1 parent 837cf6b commit cd5c166

File tree

7 files changed

+318
-31
lines changed

7 files changed

+318
-31
lines changed

libraries/ESP8266WebServer/README.rst

+20-1
Original file line numberDiff line numberDiff line change
@@ -54,8 +54,10 @@ Client request handlers
5454

5555
.. code:: cpp
5656
57-
void on();
57+
RequestHandler<ServerType>& on();
58+
bool removeRoute();
5859
void addHandler();
60+
bool removeHandler();
5961
void onNotFound();
6062
void onFileUpload();
6163
@@ -64,9 +66,26 @@ Client request handlers
6466
.. code:: cpp
6567
6668
server.on("/", handlerFunction);
69+
server.removeRoute("/"); // Removes any route which points to "/" and has HTTP_ANY attribute
70+
server.removeRoute("/", HTTP_GET); // Removes any route which points to "/" and has HTTP_GET attribute
6771
server.onNotFound(handlerFunction); // called when handler is not assigned
6872
server.onFileUpload(handlerFunction); // handle file uploads
6973
74+
Client request filters
75+
^^^^^^^^^^^^^^^^^^^^^^
76+
77+
.. code:: cpp
78+
79+
RequestHandler<ServerType>& setFilter();
80+
81+
*Example:*
82+
83+
More details about this in `Filters.ino` example.
84+
85+
.. code:: cpp
86+
87+
server.on("/", handlerFunction).setFilter(ON_AP_FILTER)
88+
7089
Sending responses to the client
7190
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
7291

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
#include <ESP8266WiFi.h>
2+
#include <WiFiClient.h>
3+
#include <ESP8266WebServer.h>
4+
#include <ESP8266mDNS.h>
5+
6+
// Your STA WiFi Credentials
7+
// ( This is the AP your ESP will connect to )
8+
const char *ssid = "...";
9+
const char *password = "...";
10+
11+
// Your AP WiFi Credentials
12+
// ( This is the AP your ESP will broadcast )
13+
const char *ap_ssid = "ESP8266_Demo";
14+
const char *ap_password = "";
15+
16+
ESP8266WebServer server(80);
17+
18+
const int led = 13;
19+
20+
// ON_STA_FILTER - Only accept requests coming from STA interface
21+
bool ON_STA_FILTER(ESP8266WebServer &server) {
22+
return WiFi.localIP() == server.client().localIP();
23+
}
24+
25+
// ON_AP_FILTER - Only accept requests coming from AP interface
26+
bool ON_AP_FILTER(ESP8266WebServer &server) {
27+
return WiFi.softAPIP() == server.client().localIP();
28+
}
29+
30+
void handleNotFound() {
31+
digitalWrite(led, 1);
32+
String message = "File Not Found\n\n";
33+
message += "URI: ";
34+
message += server.uri();
35+
message += "\nMethod: ";
36+
message += (server.method() == HTTP_GET) ? "GET" : "POST";
37+
message += "\nArguments: ";
38+
message += server.args();
39+
message += "\n";
40+
for (uint8_t i = 0; i < server.args(); i++) {
41+
message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
42+
}
43+
server.send(404, "text/plain", message);
44+
digitalWrite(led, 0);
45+
}
46+
47+
void setup(void) {
48+
pinMode(led, OUTPUT);
49+
digitalWrite(led, 0);
50+
Serial.begin(115200);
51+
WiFi.mode(WIFI_AP_STA);
52+
// Connect to STA
53+
WiFi.begin(ssid, password);
54+
// Start AP
55+
WiFi.softAP(ap_ssid, ap_password);
56+
Serial.println("");
57+
58+
// Wait for connection
59+
while (WiFi.status() != WL_CONNECTED) {
60+
delay(500);
61+
Serial.print(".");
62+
}
63+
Serial.println("");
64+
Serial.print("Connected to ");
65+
Serial.println(ssid);
66+
Serial.print("IP address: ");
67+
Serial.println(WiFi.localIP());
68+
69+
if (MDNS.begin("esp8266")) {
70+
Serial.println("MDNS responder started");
71+
}
72+
73+
// This route will be accessible by STA clients only
74+
server.on("/", [&]() {
75+
digitalWrite(led, 1);
76+
server.send(200, "text/plain", "Hi!, This route is accessible for STA clients only");
77+
digitalWrite(led, 0);
78+
})
79+
.setFilter(ON_STA_FILTER);
80+
81+
// This route will be accessible by AP clients only
82+
server.on("/", [&]() {
83+
digitalWrite(led, 1);
84+
server.send(200, "text/plain", "Hi!, This route is accessible for AP clients only");
85+
digitalWrite(led, 0);
86+
})
87+
.setFilter(ON_AP_FILTER);
88+
89+
server.on("/inline", []() {
90+
server.send(200, "text/plain", "this works as well");
91+
});
92+
93+
server.onNotFound(handleNotFound);
94+
95+
server.begin();
96+
Serial.println("HTTP server started");
97+
}
98+
99+
void loop(void) {
100+
server.handleClient();
101+
}

libraries/ESP8266WebServer/src/ESP8266WebServer-impl.h

+81-6
Original file line numberDiff line numberDiff line change
@@ -230,25 +230,73 @@ void ESP8266WebServerTemplate<ServerType>::requestAuthentication(HTTPAuthMethod
230230
}
231231

232232
template <typename ServerType>
233-
void ESP8266WebServerTemplate<ServerType>::on(const Uri &uri, ESP8266WebServerTemplate<ServerType>::THandlerFunction handler) {
234-
on(uri, HTTP_ANY, handler);
233+
RequestHandler<ServerType>& ESP8266WebServerTemplate<ServerType>::on(const Uri &uri, ESP8266WebServerTemplate<ServerType>::THandlerFunction handler) {
234+
return on(uri, HTTP_ANY, handler);
235235
}
236236

237237
template <typename ServerType>
238-
void ESP8266WebServerTemplate<ServerType>::on(const Uri &uri, HTTPMethod method, ESP8266WebServerTemplate<ServerType>::THandlerFunction fn) {
239-
on(uri, method, fn, _fileUploadHandler);
238+
RequestHandler<ServerType>& ESP8266WebServerTemplate<ServerType>::on(const Uri &uri, HTTPMethod method, ESP8266WebServerTemplate<ServerType>::THandlerFunction fn) {
239+
return on(uri, method, fn, _fileUploadHandler);
240240
}
241241

242242
template <typename ServerType>
243-
void ESP8266WebServerTemplate<ServerType>::on(const Uri &uri, HTTPMethod method, ESP8266WebServerTemplate<ServerType>::THandlerFunction fn, ESP8266WebServerTemplate<ServerType>::THandlerFunction ufn) {
244-
_addRequestHandler(new FunctionRequestHandler<ServerType>(fn, ufn, uri, method));
243+
RequestHandler<ServerType>& ESP8266WebServerTemplate<ServerType>::on(const Uri &uri, HTTPMethod method, ESP8266WebServerTemplate<ServerType>::THandlerFunction fn, ESP8266WebServerTemplate<ServerType>::THandlerFunction ufn) {
244+
RequestHandler<ServerType> *handler = new FunctionRequestHandler<ServerType>(fn, ufn, uri, method);
245+
_addRequestHandler(handler);
246+
return *handler;
247+
}
248+
249+
template <typename ServerType>
250+
bool ESP8266WebServerTemplate<ServerType>::removeRoute(const char *uri) {
251+
return removeRoute(String(uri), HTTP_ANY);
252+
}
253+
254+
template <typename ServerType>
255+
bool ESP8266WebServerTemplate<ServerType>::removeRoute(const char *uri, HTTPMethod method) {
256+
return removeRoute(String(uri), method);
257+
}
258+
259+
template <typename ServerType>
260+
bool ESP8266WebServerTemplate<ServerType>::removeRoute(const String &uri) {
261+
return removeRoute(uri, HTTP_ANY);
262+
}
263+
264+
template <typename ServerType>
265+
bool ESP8266WebServerTemplate<ServerType>::removeRoute(const String &uri, HTTPMethod method) {
266+
bool anyHandlerRemoved = false;
267+
RequestHandlerType *handler = _firstHandler;
268+
RequestHandlerType *previousHandler = nullptr;
269+
270+
while (handler) {
271+
if (handler->canHandle(method, uri)) {
272+
if (_removeRequestHandler(handler)) {
273+
anyHandlerRemoved = true;
274+
// Move to the next handler
275+
if (previousHandler) {
276+
handler = previousHandler->next();
277+
} else {
278+
handler = _firstHandler;
279+
}
280+
continue;
281+
}
282+
}
283+
previousHandler = handler;
284+
handler = handler->next();
285+
}
286+
287+
return anyHandlerRemoved;
245288
}
246289

247290
template <typename ServerType>
248291
void ESP8266WebServerTemplate<ServerType>::addHandler(RequestHandlerType* handler) {
249292
_addRequestHandler(handler);
250293
}
251294

295+
template <typename ServerType>
296+
bool ESP8266WebServerTemplate<ServerType>::removeHandler(RequestHandlerType *handler) {
297+
return _removeRequestHandler(handler);
298+
}
299+
252300
template <typename ServerType>
253301
void ESP8266WebServerTemplate<ServerType>::_addRequestHandler(RequestHandlerType* handler) {
254302
if (!_lastHandler) {
@@ -261,6 +309,33 @@ void ESP8266WebServerTemplate<ServerType>::_addRequestHandler(RequestHandlerType
261309
}
262310
}
263311

312+
template <typename ServerType>
313+
bool ESP8266WebServerTemplate<ServerType>::_removeRequestHandler(RequestHandlerType *handler) {
314+
RequestHandlerType *current = _firstHandler;
315+
RequestHandlerType *previous = nullptr;
316+
317+
while (current != nullptr) {
318+
if (current == handler) {
319+
if (previous == nullptr) {
320+
_firstHandler = current->next();
321+
} else {
322+
previous->next(current->next());
323+
}
324+
325+
if (current == _lastHandler) {
326+
_lastHandler = previous;
327+
}
328+
329+
// Delete 'matching' handler
330+
delete current;
331+
return true;
332+
}
333+
previous = current;
334+
current = current->next();
335+
}
336+
return false;
337+
}
338+
264339
template <typename ServerType>
265340
void ESP8266WebServerTemplate<ServerType>::serveStatic(const char* uri, FS& fs, const char* path, const char* cache_header) {
266341
bool is_file = false;

libraries/ESP8266WebServer/src/ESP8266WebServer.h

+11-4
Original file line numberDiff line numberDiff line change
@@ -116,11 +116,17 @@ class ESP8266WebServerTemplate
116116

117117
typedef std::function<void(void)> THandlerFunction;
118118
typedef std::function<String(FS &fs, const String &fName)> ETagFunction;
119-
120-
void on(const Uri &uri, THandlerFunction handler);
121-
void on(const Uri &uri, HTTPMethod method, THandlerFunction fn);
122-
void on(const Uri &uri, HTTPMethod method, THandlerFunction fn, THandlerFunction ufn);
119+
typedef std::function<bool(ESP8266WebServerTemplate<ServerType> &server)> FilterFunction;
120+
121+
RequestHandler<ServerType>& on(const Uri &uri, THandlerFunction handler);
122+
RequestHandler<ServerType>& on(const Uri &uri, HTTPMethod method, THandlerFunction fn);
123+
RequestHandler<ServerType>& on(const Uri &uri, HTTPMethod method, THandlerFunction fn, THandlerFunction ufn);
124+
bool removeRoute(const char *uri);
125+
bool removeRoute(const char *uri, HTTPMethod method);
126+
bool removeRoute(const String &uri);
127+
bool removeRoute(const String &uri, HTTPMethod method);
123128
void addHandler(RequestHandlerType* handler);
129+
bool removeHandler(RequestHandlerType* handler);
124130
void serveStatic(const char* uri, fs::FS& fs, const char* path, const char* cache_header = NULL );
125131
void onNotFound(THandlerFunction fn); //called when handler is not assigned
126132
void onFileUpload(THandlerFunction fn); //handle file uploads
@@ -306,6 +312,7 @@ class ESP8266WebServerTemplate
306312

307313
protected:
308314
void _addRequestHandler(RequestHandlerType* handler);
315+
bool _removeRequestHandler(RequestHandlerType *handler);
309316
void _handleRequest();
310317
void _finalizeResponse();
311318
ClientFuture _parseRequest(ClientType& client);

libraries/ESP8266WebServer/src/Parsing-impl.h

+6-6
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,7 @@ typename ESP8266WebServerTemplate<ServerType>::ClientFuture ESP8266WebServerTemp
106106
//attach handler
107107
RequestHandlerType* handler;
108108
for (handler = _firstHandler; handler; handler = handler->next()) {
109-
if (handler->canHandle(_currentMethod, _currentUri))
109+
if (handler->canHandle(*this, _currentMethod, _currentUri))
110110
break;
111111
}
112112
_currentHandler = handler;
@@ -324,7 +324,7 @@ int ESP8266WebServerTemplate<ServerType>::_parseArgumentsPrivate(const String& d
324324
template <typename ServerType>
325325
void ESP8266WebServerTemplate<ServerType>::_uploadWriteByte(uint8_t b){
326326
if (_currentUpload->currentSize == HTTP_UPLOAD_BUFLEN){
327-
if(_currentHandler && _currentHandler->canUpload(_currentUri))
327+
if(_currentHandler && _currentHandler->canUpload(*this, _currentUri))
328328
_currentHandler->upload(*this, _currentUri, *_currentUpload);
329329
_currentUpload->totalSize += _currentUpload->currentSize;
330330
_currentUpload->currentSize = 0;
@@ -425,7 +425,7 @@ bool ESP8266WebServerTemplate<ServerType>::_parseForm(ClientType& client, const
425425
_currentUpload->currentSize = 0;
426426
_currentUpload->contentLength = len;
427427
DBGWS("Start File: %s Type: %s\n", _currentUpload->filename.c_str(), _currentUpload->type.c_str());
428-
if(_currentHandler && _currentHandler->canUpload(_currentUri))
428+
if(_currentHandler && _currentHandler->canUpload(*this, _currentUri))
429429
_currentHandler->upload(*this, _currentUri, *_currentUpload);
430430
_currentUpload->status = UPLOAD_FILE_WRITE;
431431

@@ -463,11 +463,11 @@ bool ESP8266WebServerTemplate<ServerType>::_parseForm(ClientType& client, const
463463
}
464464
}
465465
// Found the boundary string, finish processing this file upload
466-
if (_currentHandler && _currentHandler->canUpload(_currentUri))
466+
if (_currentHandler && _currentHandler->canUpload(*this, _currentUri))
467467
_currentHandler->upload(*this, _currentUri, *_currentUpload);
468468
_currentUpload->totalSize += _currentUpload->currentSize;
469469
_currentUpload->status = UPLOAD_FILE_END;
470-
if (_currentHandler && _currentHandler->canUpload(_currentUri))
470+
if (_currentHandler && _currentHandler->canUpload(*this, _currentUri))
471471
_currentHandler->upload(*this, _currentUri, *_currentUpload);
472472
DBGWS("End File: %s Type: %s Size: %d\n",
473473
_currentUpload->filename.c_str(),
@@ -542,7 +542,7 @@ String ESP8266WebServerTemplate<ServerType>::urlDecode(const String& text)
542542
template <typename ServerType>
543543
bool ESP8266WebServerTemplate<ServerType>::_parseFormUploadAborted(){
544544
_currentUpload->status = UPLOAD_FILE_ABORTED;
545-
if(_currentHandler && _currentHandler->canUpload(_currentUri))
545+
if(_currentHandler && _currentHandler->canUpload(*this, _currentUri))
546546
_currentHandler->upload(*this, _currentUri, *_currentUpload);
547547
return false;
548548
}

0 commit comments

Comments
 (0)