14

I have noticed something in the Spark Framework. It does not match trailing slashes with a mapped route. So it considers /api/test and /api/test/ as different URIs.

That's fine if there is a way to wildcard them together, but there doesn't seem to be. Am I missing anything?

I want this route:

Spark.get("/api/test", (req, res) -> {
            return "TEST OK";
        });

To match /api/test OR /api/test/. As it stands, it only matches /api/test, and if I switch it to:

Spark.get("/api/test/", (req, res) -> {
            return "TEST OK";
        });

It only matches /api/test/

mtyson
  • 8,196
  • 16
  • 66
  • 106
  • I know nothing of spark... but if the URI isa regex, then you could add a **?** after the last **/**. – Augusto Jan 12 '16 at 20:36

2 Answers2

12

You can setup a before filter with a redirect, such as:

Spark.before((req, res) -> {
    String path = req.pathInfo();
    if (path.endsWith("/"))
        res.redirect(path.substring(0, path.length() - 1));
});

This is probably better than mapping duplicate routes.

Rafael Martins
  • 548
  • 5
  • 8
7

It seems to be asked before in 2013, but closed (and I assume not implemented) in 2015:

https://github.com/perwendel/spark/issues/97

Routes should match with and without trailing slash #97

jsnoriegam opened this issue on Aug 31, 2013

ryber added a commit to ryber/spark that referenced this issue on Oct 14, 2013

tipsy added the Feature request label on Nov 22, 2015

perwendel closed this on Nov 23, 2015

There was a pull request by ryber with a fix for this issue:

https://github.com/ryber/spark/commit/556597e679dc224719188f8d27d8ba10e58fd8bb

However, this does not seem to be part of the current SimpleRouteMatcher class:

https://github.com/perwendel/spark/blob/ded78b7fa9b78749c0d5f6776bba9c9cd3cfb6fb/src/main/java/spark/route/SimpleRouteMatcher.java

Community
  • 1
  • 1
Freek de Bruijn
  • 3,552
  • 2
  • 22
  • 28
  • I suppose I'll have to map each route both with and without a trailing slash. Bleh. – mtyson Jan 12 '16 at 21:31
  • Or dive into the Spark code and suggest another pull request, but it's not clear whether that will be accepted. Good luck anyway. – Freek de Bruijn Jan 12 '16 at 21:33
  • I think usually (e.g. Sinatra?) will allow a regex, so you'd be able to end with `/?`. That could be nice. – Max Jan 13 '16 at 22:50