Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get list of all Route URL strings in play framework?

I have many controllers in my play 2.4.x application.

I want to get a list of all route URLs pointing their respective controllers. I know how to get the URL from the current request. But I need a list of all the URLs available inside a play application.I want to generate this list dynamically because URLs can be changed/added/deleted in future.

So,is there some way I can generate this URL list dynamically ? Or do I have the obligation to store all the URLs statically somewhere in cache or dictionary ?

like image 497
oblivion Avatar asked Jun 20 '17 10:06

oblivion


People also ask

In which folder does play expect routes file?

The conf/routes file is the configuration file used by the Router. This file lists all the routes needed by the application.

Which play component is in charge of mapping incoming request URL into action?

The router is the component in charge of translating incoming HTTP Requests into action calls (a static, public method of a Controller).

What is routes scala?

The routes file syntax conf/routes is the configuration file used by the router. This file lists all of the routes needed by the application. Each route consists of an HTTP method and URI pattern, both associated with a call to an Action generator.


2 Answers

I obtained the desired list by using the documentation method provided by Router trait. The documentation method returns Seq[(String, String, String)] .Here each tuple has the format:

( {http-method} , {url} , {controller method} )

The Router trait is extended by all the autogenerated Routes.scala classes. Scala-compiler generated a separate Routes.scala for each routes file in the application. These auto-generated Routes.scala files implement all the methods of Router trait including the documentation method that we discussed above.

So,to get list of all URLs, I simply had to inject the Router trait and then access the documentation method:

import play.api.routing.Router

class MyClass @Inject()(router: Router) {
 def getAllURLs:Seq[String] = router.documentation.map(k => k._2)
}
like image 65
oblivion Avatar answered Nov 04 '22 01:11

oblivion


Update for Play 2.7, Scala:

class MyController @Inject()(routesProvider: Provider[play.api.routing.Router]) { lazy val routes: Seq[(String, String, String)] = routesProvider.get.documentation }

from discussion for play 2.6

like image 38
mipasov Avatar answered Nov 04 '22 01:11

mipasov