Malcolm Crum
Malcolm Crum

Reputation: 4879

SparkJava: Get route path from request

If I have a route like foo/:id in my SparkJava server, I want to get that route string in my handler. I can get the pathInfo as in the following:

Spark.get("foo/:id", (request, response) -> {
   var matchedRoute = request.pathInfo();
   System.out.println(matchedRoute);
})

But if I curl localhost:8080/foo/1, then this will print /foo/1, instead of /foo/:id.

Is it possible to get the route that SparkJava matched the request against?

Upvotes: 0

Views: 947

Answers (1)

SHG
SHG

Reputation: 2616

There's no inherent way to do that because the anonymous function doesn't receive the route itself as an argument. But you could add the route to the request in a 'before' part:

// For every route add these two lines:
String API_PATH_1 = "foo/:id";
before(API_PATH_1, (req, res) -> req.attribute("route", API_PATH_1));

get(API_PATH_1, (req, res) -> {
    String route = req.attribute("route");
    String matchedRoute = req.pathInfo();
    System.out.println("Route:         " + route);
    System.out.println("Matched Route: " + matchedRoute);
});

It adds a little bit of code but if you're consistent with this pattern with all your routes then in the get() part you can always just call req.attribute("route") which will give you what wanted.

Upvotes: 1

Related Questions