10

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?

Sam Jones
  • 1,400
  • 1
  • 13
  • 25

3 Answers3

5

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 );
...
Daniel De León
  • 13,196
  • 5
  • 87
  • 72
3

I found a workaround in an example. I can have my not found handler examine the uri directly and handle this case. IE,

void handleDirection(String path) {
  int index = path.lastIndexOf('/');
  String direction = path.substring(index, path.length());
  Serial.println(direction);
}

void handleNotFound() {
  String path = server.uri();
  int index = path.indexOf("/robot");
  if (index >= 0) {
    handleDirection(path);
  }

  returnNotFound();
}

void setup() {
    [...]
    server.onNotFound ( handleNotFound );
    [...]
}

It works for now. I'll leave the question unanswered in case someone else finds the right way to do it.

Sam Jones
  • 1,400
  • 1
  • 13
  • 25
3

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.

Mohammed Noureldin
  • 14,913
  • 17
  • 70
  • 99