Setting a wildcard in ESP8266WebServer

Viewed 2245

I want to send all paths that start with "/robot" to a certain handler using ESP8266WebServer.h. I tried a few variations:

server.on ( "/robot", handleDirection );
server.on ( "/robot/", handleDirection );
server.on ( "/robot/*", handleDirection );

But in each case, it only listens for the exact path (including the * for that one).

Does this library just not support wildcard paths? Or am I missing how to do it?

3 Answers

This is very easy in OO way

class MyHandler : public RequestHandler {

  bool canHandle(HTTPMethod method, String uri) {
    return uri.startsWith( "/robot" );
  }

  bool handle(ESP8266WebServer& server, HTTPMethod requestMethod, String requestUri) {    
    doRobot( requestUri );
    server.send(200, "text/plain", "Yes!!");
    return true;
  }

} myHandler;

...
  server.addHandler( &myHandler );
...

TL;DR

You can achieve this by doing the following using regular expressions:

#include <uri/UriRegex.h>

web_server.on(UriRegex("/home/([0-9]+)/first"), HTTP_GET, [&]() {
    web_server.send(200, "text/plain", "Hello from first! URL arg: " + web_server.pathArg(0));
});

web_server.on(UriRegex("/home/([0-9]+)/second"), HTTP_GET, [&]() {
    web_server.send(200, "text/plain", "Hello from second! URL arg: " + web_server.pathArg(0));
});

Then try to call the URLs like this:

http://<IP ADDRESS>/home/123/first

Then you should see the following in your browser!

Hello from first! URL arg: 123

Please notice that every RegEx group will correspond to a pathArg.

More options:

After checking the source code of Arduino framework for ESP, and according to the following file, pull request and issue on GitHub, it is stated in this comment that you have three options:

Option 1: proposal by @Bmooij with custom "{}" for wildcard and pathArgs in #5214
Option 2: glob style pattern matching, which is super standard and used in most shells in #5467
Option 3: regex pattern matching, which is also super standard, although a bit more complex.

Related